代码之家  ›  专栏  ›  技术社区  ›  Miha Å uÅ¡terÅ¡ič

Axios,fetch()将请求头设置为访问控制请求头,而不是单独的头

  •  1
  • Miha Å uÅ¡terÅ¡ič  · 技术社区  · 6 年前

    这是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
            }
          }
        );
    

    结果是一样的。

    这是浏览器服务器通信的问题吗?如果是的话,响应头中是否缺少一些内容?

    对邮递员做同样的请求也行。

    2 回复  |  直到 6 年前
        1
  •  0
  •   sideshowbarker Miguel Tomás    6 年前

    问题中显示的预飞行的响应头表示服务器没有发回响应 Access-Control-Allow-Methods

    为了让浏览器认为预飞是成功的,它需要服务器响应同时包含 Access-Control-Allow-Headers 访问控制允许方法 响应标头。

        2
  •  0
  •   Kris Witalewski    6 年前