尽管在Express中设置了Access-Control-Allow-Origin,但请求标头字段仍为授权

时间:2018-09-12 11:06:46

标签: node.js express vue.js axios

我已经使用Vue-cli制作了Vue.js应用,并希望从后端使用受限制的api。

为了避免发生CORS问题,我在应用程序的server.js中对此进行了设置:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Credentials", "true");
    res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
    res.header("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");

  next();
});

但是,当我从Vue.js组件发出带有授权标头的请求时:

 axios.get('http://127.0.0.1:3000/api/article', headerConfig)
        .then( res => this.article = res.data)
         .catch(error => console.log(error))            
    }

我仍然得到:

Failed to load http://127.0.0.1:3000/api/article: Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

感谢您的帮助以解决此问题。

1 个答案:

答案 0 :(得分:1)

您必须明确允许“ Authorization”标头用于跨域请求,并提到了Access-Control-Allow-Headers标头:

res.header("Access-Control-Allow-Headers", "X-Requested-With, Authorization");

they are "simple" headers以来,CORS实际上不需要提及大多数标头,因为有dedicated list

它与您仅显式发送的标头有关。 假设originaccess-control-request-headers由浏览器生成以进行预检-除非没有明确发送它们,否则您也无需列出Access-Control-Allow-Headers作为响应。