zoukankan      html  css  js  c++  java
  • 解决前后端分离后的Cookie跨域问题


    一. 前端Ajax关键配置

    $.ajax({
      type: "post",
      url: xxx,
      data: xxx,
      contentType: 'application/json',
      dataType: "json",
      xhrFields: {
          withCredentials: true
      },
    
      success: function (data) {
      }
    })

     

    二、后端过滤器关键配置

      //解决Cookie跨域问题
      response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
      response.setHeader("Access-Control-Allow-Credentials", "true");
      response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      response.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE");
    
      //解决 Content-Type:application/json 时跨域设置失败问题
      if("OPTIONS".equals(request.getMethod())) {
          //放行OPTIONS请求
          filterChain.doFilter(request, response);
          return;
      }

    注意:

    • "Access-Control-Allow-Origin" 不能设置成 "*"
    • 当 Content-Type 为 application/json 时,Ajax实际会发两次请求,第一次是一个OPTIONS请求,这时过滤器一定得放开

      

     

  • 相关阅读:
    软件需求与分析课堂讨论
    Axios
    lodash
    table行拖拽
    js addDays ,addYears
    所在周的第一天
    Inner join case when
    npm 淘宝镜像安装以及安装报错window_nt 6.1.7601 解决
    jsTree
    Bootstrap Multiselect
  • 原文地址:https://www.cnblogs.com/gdufs/p/8442648.html
Copyright © 2011-2022 走看看