fetch异步请求数据报错d content-type is not allowed by Access-Control-Allow-Headers in pr

103 阅读1分钟

在使用node搭建服务的时候,使用fetch发送请求,返回json数据无法接收使用,此时需要修改node的服务端 跨域访问设置为:

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Headers', ' Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    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();
})

其中可以解决上图报错的代码是:

1,

  res.header('Access-Control-Allow-Headers', ' Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');

2,

  res.header("Content-Type", "application/json;charset=utf-8");
    next();

②中设定返回数据的类型为json,此时需要把②的Content-Type设定在①中的Access-Control-Allow-Headers中,此时可以解决报错问题

前提必须是允许跨域访问:

  res.header("Access-Control-Allow-Origin", "*");