Axios,fetch()将请求标头设置为Access-Control-Request-Headers而不是单独的标头

问题描述 投票:1回答:2

我正在尝试使用来自react应用程序的一些自定义标头发出GET请求。

这是axios拦截器的代码:

addCaptchaHeaders(captcha, sgn, exp) {
    // remove the old captcha headers
    if (this.captchaHeadersInterceptor !== undefined) {
      this.removeCaptchaHeader();
    }
    // Sign new captcha headers
    this.captchaHeadersInterceptor = this.httpClient.interceptors.request.use(
      config => {
        // Add headers here
        config.headers.common._captcha = captcha;
        config.headers.common._sgn = sgn;
        config.headers.common._exp = exp;
        return config;
      },
      error => {
        // Do something with request error
        return Promise.reject(error);
      }
    );
  }

这些是预检请求的响应标头:

Access-Control-Allow-Headers: origin, content-type, accept, authorization, _captcha, _sgn, _exp
Content-Length: 0
Server: Jetty(9.3.24.v20180605)

这些是预检请求的请求标头:

Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,sl;q=0.8
Access-Control-Request-Headers: _captcha,_exp,_sgn
Access-Control-Request-Method: GET
Connection: keep-alive
Host: localhost:8086
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36

预检后的实际请求的标题是相同的。所以Access-Control-Request-Headers: _captcha,_exp,_sgn而不是自定义请求标头。

认为这是一个axios配置问题我使用fetch做了相同的请求:

fetch(
      "http://localhost:8086/podatki/parcela/search?parcela=1727&count=50&offset=0",
      {
        method: "GET",
        headers: {
          _captcha: res,
          _sgn: sgn,
          _exp: exp
        }
      }
    );

结果是一样的。

这是浏览器 - 服务器通信的问题吗?如果是这样,响应标题中缺少一些东西?

与邮递员一起做同样的请求。

javascript http cors http-headers fetch-api
2个回答
0
投票

问题中显示的预检的响应标头表明服务器没有发回Access-Control-Allow-Methods响应头。

为了让浏览器认为预检成功,需要服务器响应包括Access-Control-Allow-HeadersAccess-Control-Allow-Methods响应头。


0
投票

你在哪里查看标题? Chrome开发工具确实会像这样显示它们,但只有当请求无法加载时(由于缺少“Access-Control-Allow-Origin”标题 - 在这种情况下即使服务器返回200也会失败 - 或者出于任何其他原因)

© www.soinside.com 2019 - 2024. All rights reserved.