账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    JavaScript 使用 headers > Authorization 存放 token 出现跨域错误?
    21
    0

    在设置了 headers 请求头中的 Authorization 后出现了这个问题

    请求异常

    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 = "*";
                    //允许以下请求方法
                    String allowMethods = "GET,POST,PUT,DELETE,OPTIONS";
                    //允许以下请求头
                    String allowHeaders = "Content-Type,X-Token";
                    //允许有认证信息(cookie)
                    String allowCredentials = "true";
    
                    String origin = request.getHeader("Origin");
                    //此处是为了兼容需要认证信息(cookie)的时候不能设置为 * 的问题
                    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);
                }
            };
        }
    }

    请问上面的代码有什么问题么?为什么明明处理过了结果还是会出现跨域问题呢?

    1
    打赏
    收藏
    点击回答
        全部回答
    • 共 0 条
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部