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

<?php
header('Access-Control-Allow-Origin:http://a.cn');
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 {
    @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
比如
ajax跨域请求不携带cookies,设置前端withCredentials: true和后端Access-Control-Allow-Credentials true_第1张图片
ajax跨域请求不携带cookies,设置前端withCredentials: true和后端Access-Control-Allow-Credentials true_第2张图片
解决方案

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

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

你可能感兴趣的:(#,JavaScript,ajax,http,前后端分离)