在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java  HTML/ JavaScript 使用 headers > Authorization

JavaScript 使用 headers > Authorization 存放 token 出現(xiàn)跨域錯(cuò)誤?

在設(shè)置了 headers 請(qǐng)求頭中的 Authorization 后出現(xiàn)了這個(gè)問題

請(qǐng)求異常

Failed to load http://host:port/auth/user/updatePassword: Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

JavaScript 代碼

// 修改密碼
var fd = new FormData()
fd.append('password', '123456789')
fetch(ctx + '/auth/user/updatePassword', {
  method: 'post',
  credentials: 'include',
  headers: {
    'Authorization': '39058cb8ec7ee5bde4e8813857a5e6591edf5da2eb997ba8416cf711d083c46ea94a3344f1d8670eaa7a8896ac71e6fdbe90c75b1c579fd52368c82f44777473'
  },
  body: fd
})
  .then(res => res.json())
  .then(json => console.log(json))

Java 處理跨域的代碼

@Configuration
public class CorsConfig {
    @Bean
    public OncePerRequestFilter corsFilter() {
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
                //允許所有來源
                String allowOrigin = "*";
                //允許以下請(qǐng)求方法
                String allowMethods = "GET,POST,PUT,DELETE,OPTIONS";
                //允許以下請(qǐng)求頭
                String allowHeaders = "Content-Type,X-Token";
                //允許有認(rèn)證信息(cookie)
                String allowCredentials = "true";

                String origin = request.getHeader("Origin");
                //此處是為了兼容需要認(rèn)證信息(cookie)的時(shí)候不能設(shè)置為 * 的問題
                response.setHeader("Access-Control-Allow-Origin", origin == null ? allowOrigin : origin);
                response.setHeader("Access-Control-Allow-Methods", allowMethods);
                response.setHeader("Access-Control-Allow-Credentials", allowCredentials);
                response.setHeader("Access-Control-Allow-Headers", allowHeaders);
                filterChain.doFilter(request, response);
            }
        };
    }
}

請(qǐng)問上面的代碼有什么問題么?為什么明明處理過了結(jié)果還是會(huì)出現(xiàn)跨域問題呢?

回答
編輯回答
爆扎

試試把 Authorization 加到 allowHeaders 里面

2018年7月18日 03:46