我的node项目目录如下
方法一:可以直接在app.js文件中设置如下
//跨域问题解决方面
app.all('*',function (req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:8080','http://localhost:8081');//可设置多个跨域
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
res.header('Access-Control-Allow-Credentials',true)//允许客户端携带验证信息
next();
});
方法二:先安装cors依赖,即npm install cors,在app.js中设置如下
//跨域问题解决方面
const cors = require('cors');
app.use(cors({
origin: ['http://localhost:8080','http://localhost:8081'],//可设置多个跨域
credentials: true//允许客户端携带验证信息
}))
个人建议使用第二种方法比较好,代码也比较简洁