当前位置: 首页 > 知识库问答 >
问题:

Access-Control-Allow-Headers错误不允许请求头字段授权

段哲圣
2023-03-14
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', req.headers.origin);
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    next();
}
app.use(allowCrossDomain);
import axios from 'axios'

export default axios.create({
  baseURL: 'https://example.com',
  timeout: 5000,
  headers: {
    'Authorization': 'Bearer ' + accessToken
  }
})

请求头字段access-control-allow-headers本身在飞行前响应中是不允许的

共有1个答案

姜乐语
2023-03-14

问题中的代码显然没有导致access-control-allog-headers标头为选项响应而被发送,特别是为对CORS preflight选项的响应而发送。

为了确保正确处理预置选项,请考虑安装npmcors包:

npm install cors

然后做这样的事情:

var express = require('express')
  , cors = require('cors')
  , app = express();
app.options('*', cors()); // preflight OPTIONS; put before other routes
 类似资料: