【问题标题】:CORS policy: Request header field token is not allowed by Access-Control-Allow-HeadersCORS 策略:Access-Control-Allow-Headers 不允许请求标头字段令牌
【发布时间】:2021-12-16 11:31:47
【问题描述】:

我正在向一个请求两个身份验证标头的 api 发出 GET 类型请求,其中一个称为令牌,另一个称为身份验证。

我正在传递两个必需的参数,如下面的打印屏幕所示:

作为回报,我得到了错误:

Access to XMLHttpRequest at 'https://pay.apiname.com.br/v1/sellers/d.....2/payments/list' from origin 'http://10.0.0.150:3006' has been blocked by CORS policy: Request header field token is not allowed by Access-Control-Allow-Headers in preflight response.

我正在使用 axios 发出请求。在下面的文件中,您可以配置此特定中间件的请求。我什至在必要时在 redux 操作中运行此请求。

paymentApi: {
    client: axios.create({
      baseURL: process.env.API,
      responseType: 'json',
    }),
    options: {
      returnRejectedPromiseOnError: true,
      interceptors: {
        request: [
          ({ getState }, config) => {
            // here I look for the user information from the state, where it contains the authorization and token needed for the header.
            const { auth } = getState().get('login').toJS();

            return {
              ...config,
              headers: {
                ...(config.headers || {}),
                token: auth.user.token_parcela
                  ? `${auth.user.token_parcela}`
                  : undefined,
                Authorization: auth.user.api_key_parcela
                  ? `${auth.user.api_key_parcela}`
                  : undefined,
                Accept: 'application/json',
                'Content-Type': 'application/json',
              },
            };
          },
        ],
        response: [
          {
            success: (store, response) => response,
            error: (_store, error) => {
              console.error(error);
              return Promise.reject(error);
            },
          },
        ],
      },
    },
  },
  

奇怪的是,如果你尝试使用邮递员提出这个请求,我可以毫无问题地做到这一点,请参见下面的打印屏幕。

【问题讨论】:

  • 我怀疑您可能误解了 API 文档。或者,文档有误,API 中有错误,或者该端点不适合 Web 客户端使用。

标签: reactjs api rest redux axios


【解决方案1】:

该问题与您的代码无关,托管/构建它的 API 需要允许 CORS 来源,并且您必须指定您从中调用此 API 的网站作为来源。

在此处阅读有关 CORS 的更多信息 - CORS

它也适用于 Postman 是因为 API 是直接调用的,而不是像您的代码那样来自任何来源/来源/网站。

【讨论】:

  • 我认为问题一定出在 api 上。那里确实是个问题。
猜你喜欢
  • 2020-02-27
  • 2020-10-31
  • 2017-03-03
  • 2019-11-06
  • 1970-01-01
  • 1970-01-01
  • 2016-05-15
  • 2020-03-02
  • 2013-07-05
相关资源
最近更新 更多