NODE中解决跨域请求的问题

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

标签(空格分隔): 跨域node


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

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

---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();
});

二、node koa2中能够引入koa-cors中间件

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

以上代码则能够解决跨域问题跨域

相关文章
相关标签/搜索