ajax和axios的cookie跨域出现的问题以及解决方法

1.如果前端ajax和axios请求中使用允许携带cookie参数:

ajax设置:

$.ajax({ 

       url : '',

        data : data,

        dataType: 'json',

        type : 'POST',

        xhrFields: {

            withCredentials: true

        },        

        crossDomain: true,

        contentType: "application/json",

axios设置:

import axios from 'axios'

// 创建axios实例
const service = axios.create({
 baseURL: process.env.BASE_API, // node环境的不同,对应不同的baseURL
 timeout: 5000, // 请求的超时时间
 //设置默认请求头,使post请求发送的是formdata格式数据// axios的header默认的Content-Type好像是'application/json;charset=UTF-8',我的项目都是用json格式传输,如果需要更改的话,可以用这种方式修改
 // headers: { 
 // "Content-Type": "application/x-www-form-urlencoded"
 // },
 withCredentials: true // 允许携带cookie
})

这个时候需要注意需要后端配合设置:

header信息 Access-Control-Allow-Credentials:true

Access-Control-Allow-Origin不可以为 '*',因为 '*' 会和 Access-Control-Allow-Credentials:true 冲突,需配置指定的地址

如果后端设置 Access-Control-Allow-Origin: '*', 会有如下报错信息:

Failed to load http://localhost:8090/category/lists: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:8081' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

后端配置缺一不可,否则会出错,贴上我的后端示例:

/**
 * 跨域请求
 * @author sunll
 */
public class CorsFilter implements Filter {

    public Logger log = Logger.getLogger(this.getClass());

    private final List<String> allowedOrigins = Arrays.asList("http://192.168.3.52:3000","http://192.168.3.93:3000","http://192.168.8.132:3000","http://192.168.2.64:3000","http://adp5.admin.yunpaas.cn/admin/");
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;

        // Lets make sure that we are working with HTTP (that is, against HttpServletRequest and HttpServletResponse objects)
        if (req instanceof HttpServletRequest && res instanceof HttpServletResponse) {

            // Access-Control-Allow-Origin
            String origin = request.getHeader("Origin");
            System.out.println("origin.........."+origin);
            response.setHeader("Access-Control-Allow-Origin", allowedOrigins.contains(origin) ? origin : "");
            response.setHeader("Vary", "Origin");

            // Access-Control-Max-Age
            response.setHeader("Access-Control-Max-Age", "3600");

            // Access-Control-Allow-Credentials
            response.setHeader("Access-Control-Allow-Credentials", "true");

            // Access-Control-Allow-Methods
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");

            // Access-Control-Allow-Headers
            response.setHeader("Access-Control-Allow-Headers",
                    "Origin, X-Requested-With, Content-Type,Accept,X-Custom-Header, " + "USER-TOKEN");
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }


}
成功之后,可在请求中看到


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值