问题一:react 在跨域下,使用 axios,获取 headers 中的 Authorization。问题二:Request header field Authorization is not...

这篇主要记录2个由于跨域引起的问题

  1. react 在跨域下,使用axios,获取headers中的Authorization
  2. 在能获取到headers中的Authorization后,产生新的问题Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

实际问题

在跨域的时,客户端能够访问到一些默认响应的headers:

  • Cache-Control
  • Content-Language
  • Content-Type
  • Expires
  • Last-Modified
  • Pragma

那么默认情况下,客户端只能访问到以上headers...这是绝对不行的,因为我们要访问的是headers中的Authorizationaxios的配置代码如下(部分),

axios.interceptors.response.use((res) => {
    // do something
    // 默认情况下 res.headers.authorization 的值是undefined,headers中没有authorization
    if (res.headers.authorization) {
        sessionStorage.setItem('authorization', res.headers.authorization);
    }
    // do something
}

解决问题一办法

在服务端添加addHeader,请看这篇,服务端添加header。

response.addHeader("Access-Control-Expose-Headers", "Authorization");

这个Access-Control-Expose-Headers的作用是:
Access-Control-Expose-Headers相当于一个服务器的headers白名单,可以让客户端进行访问例如:

Access-Control-Expose-Headers: X-My-Custom-Header, X-Another-Custom-Header

这样设置完后 X-My-Custom-Header and X-Another-Custom-Header 就能被客户端所访问。

解决完获取res.headers.authorization 的值为undefined的问题,又有个新的问题。就是Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

解决问题二办法

在服务端的Access-Control-Allow-Headers中添加 Authorization,完美解决,例如:

String allowHeaders = "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With, Authorization";
response.addHeader("Access-Control-Allow-Headers", allowHeaders);

你可能感兴趣的:(问题一:react 在跨域下,使用 axios,获取 headers 中的 Authorization。问题二:Request header field Authorization is not...)