nodejs 设置响应头跨域

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26769677/article/details/82560616

1.非express

var http = require("http");
http.createServer(function (req, res) {
       // 添加响应头
        res.setHeader("Access-Control-Allow-Origin", "*"); 

        // 获取请求路径
        var pathname = url.parse(req.url).pathname;
        var query = url.parse(req.url, true).query;

        // 关闭nodejs 默认访问 favicon.ico
        if (!pathname.indexOf('/favicon.ico')) {
          return; 
        };

        // 路由器处理
        route(handle, pathname, query, res);

}).listen(8080);

2.使用express:

var express = require('express');
var app = express();
//设置跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

app.get('/getdata', function(req, res) {
    res.send({id:req.params.id, name: req.params.password});
});

app.listen(3000);
console.log('Listening on port 3000...');

如果报错Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
可能原因是header里面包含自定义字段,浏览器先发一次options请求,如果请求通过,则继续发送正式的post请求,而如果不通过则返回以上错误。

所以得在服务端配置options的请求返回,判断请求的方法是options的时候,返回ok(200)给客户端。

/*允许跨域 */
router.use(function(req, res, next) {
    //console.log(req);
    console.log(req.method);
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST,PUT,DELETE');
    res.header("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept,Authorization");
    res.header("cache-control", "no-cache");
    res.header("content-type", "application/json; charset=utf-8");
    res.header("ETag", '');
    //header头信息设置结束后,结束程序往下执行,返回
    if(req.method.toLocaleLowerCase() === 'options'){
        res.status(204);
        return res.json({});   //直接返回空数据,结束此次请求
    }else{
        next();
    }
});

还是报错的话设置Headers为:

 response.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token");

猜你喜欢

转载自blog.csdn.net/qq_26769677/article/details/82560616