300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > ajax跨域请求不携带cookies 设置前端withCredentials: true和后端Access-Control-Allow-Credentials true

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

时间:2024-03-11 15:47:50

相关推荐

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

<?phpheader('Access-Control-Allow-Origin:');header('Access-Control-Allow-Credentials:true');header('Access-Control-Allow-Methods:POST');var_dump($_POST);var_dump($_GET);var_dump(file_get_contents("php://input"));var_dump($_COOKIE);

java

//解决ajax携带cookie的跨域问题,使用@CrossOrigin注解冲突public class CorsFilter implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {}@Overridepublic 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);}@Overridepublic void destroy() {}}

或者在服务器的config设置

apache

Header set Access-Control-Allow-Credentials true

ps:遇到的问题

当使用ajax 访问 localhost 时候不会携带cookies

比如

解决方案

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

server {listen 80;server_name www.test-;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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。