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

Being blocked by CORS: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response

我遇到了错误

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 命令 post 一些数据到我的 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();
});

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

我刚刚添加了以下代码 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());