被 CORS 阻止:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段授权

Posted

技术标签:

【中文标题】被 CORS 阻止:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段授权【英文标题】:Being blocked by CORS: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response 【发布时间】:2021-08-24 00:41:53 【问题描述】:

我收到了错误

Access to XMLHttpRequest at 'http://localhost:4000/api/investments' from origin 'http://localhost:5000' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.

每当我尝试使用以下 axios 命令将一些数据发布到我的 api 时

  const [login, setLogin] = useState(
    localStorage.getItem('userInfo')
      ? JSON.parse(localStorage.getItem('userInfo'))
      : null
  );
const config = 
      headers: 
        'Content-Type': 'application/json',
        Authorization: `Bearer $login.token`,
      ,
    ;
 await axios
      .post(`$Config.SERVER_ADDRESS/api/investments`, investmentObj, config)
      .then((response) => 
        console.log(investmentObj);
        notify(`$response.data.name investimento cadastrado com Sucesso`);
        history.push(`/app/investment/$response.data._id`);
      )
      .catch((err) => 
        console.log(err);

        notify(err.response.data, 'danger');
      );

我不知道该怎么做,因为我正在使用以下中间件:

app.use((req, res, next) => 
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', '*');
  res.header('Access-Control-Allow-Credentials', true);
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'
  );

  app.use(cors());
  next();
);

我认为我的问题与标头中的授权有关,因为我的其他 api 调用正在工作......希望你们中的任何人都能帮助我处理这样的预检请求

【问题讨论】:

Authorization 添加到Access-Control-Allow-Headers 列表中是否有帮助? 【参考方案1】:

我刚刚添加了以下代码app.options('*', cors());,现在一切正常... 在 CORS npm https://www.npmjs.com/package/cors#enabling-cors-pre-flight 的文档中查看这一点

app.use((req, res, next) => 
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', '*');
  res.header('Access-Control-Allow-Credentials', true);
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'
  );

  app.use(cors( credentials: true, origin: true ));
  next();
);
app.options('*', cors());

【讨论】:

credentials: true, origin: true 非常不安全!

以上是关于被 CORS 阻止:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段授权的主要内容,如果未能解决你的问题,请参考以下文章

从源 xxxx 访问 XMLHttpRequest ' 被 CORS 策略阻止:对预检的响应。预检请求不允许重定向

被 CORS 策略阻止:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段内容类型 [重复]

JAX-RX - 被 CORS 策略阻止:预检响应中的 Access-Control-Allow-Methods 不允许方法 PATCH

角 POST 请求被 CORS 策略阻止:对预检请求的响应未通过访问控制检查

被 CORS 策略阻止:对预检的响应...没有 HTTP ok 状态。标头没有解决问题

被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP OK 状态