栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

ajax跨域请求不携带cookies,设置前端withCredentials: true和后端Access-Control-Allow-Credentials true

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ajax跨域请求不携带cookies,设置前端withCredentials: true和后端Access-Control-Allow-Credentials true

首先ajax跨域请求携带cookies

一、需要设置前端withCredentials: true

	$.ajax({
			type:'post',
			url: 'xxxxxxx',
			dataType: 'json',
			xhrFields: {
				withCredentials: true  //解决跨服务传递时不传递cookie的问题,允许携带证书
			},
			crossDomain: true,  //允许跨域
			success: function (data) {
				console.info(data)
				if (data.status == 200){
					alert(data.data)
					$("#shopping-num").html = data.data
				}
			}
		})

二、需要设置服务器或者访问的文件Access-Control-Allow-Credentials true
还需要设置 Access-Control-Allow-Origin 的域名(重点)

如果是 Access-Control-Allow-Origin * 也会发生CORS错误

比如
php

 

java

//解决ajax携带cookie的跨域问题,使用@CrossOrigin注解冲突
public class CorsFilter implements Filter {
    @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 reqs = (HttpServletRequest) req;

        // response.setHeader("Access-Control-Allow-Origin",reqs.getHeader("Origin"));
        //注意重点:下面的第二个参数不可以写*通配,需要明确写出请求方的IP地址及端口
        response.setHeader("Access-Control-Allow-Origin","http://localhost:8081");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        chain.doFilter(req, res);
    }

    @Override
    public void destroy() {

    }
}

或者在服务器的config设置
apache

    Header set Access-Control-Allow-Credentials  true

ps:遇到的问题
当使用ajax 访问 localhost 时候不会携带cookies
比如


解决方案

一、使用服务器的代理功能

server {
		listen 80;
		server_name www.test-crowdfunding.com;
		location / {
            root   E:fontweb;
            index  index.html index.htm;
        }
		
		error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
		
		location /api/ {
			proxy_pass http://localhost:9090/;
		}
	}

二、也可以把 localhost 更换127.0.0.1
localhost

127.0.0.1

猜想当在同一域名下,有两个服务器,localhost找不到是哪个服务器

比如 在同一台机器上有nginx(80端口),apache(8080端口)
当访问 localhost 时候找不到是 nginx 还是 apache

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/276830.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号