NODE中解决跨域请求的问题

1、Node Express 解决请求跨域请求

标签(空格分隔): 跨域


1是Access-Control-Allow-Origin 允许的域
2是Access-Control-Allow-Headers 允许的header类型

第一项可以直接设为* 表示任意
但是第二项不能这样写,在chrome中测试跨域发现报错,
最终的代码看起来是这个样子:

---app.js---
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    if(req.method=="OPTIONS") res.send(200);/*让options请求快速返回*/
    else  next();
});

2、node koa2中可以引入koa-cors中间件

---app.js---
const cors = require('koa-cors');
app.use(cors());

以上代码则可以解决跨域问题