AJAX跨域问题前后端配合注释事项


  1. 服务端header设置:
    $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
    if($origin == 'https://xxx.com'){
        header('Access-Control-Allow-Origin:' . $origin);
        header('Access-Control-Allow-Headers: Authorization, Origin, X-Requested-With, Content-Type, Accept');//允许凭证Authorization这个header头
        header('Access-Control-Allow-Credentials: true');
    }
    
  2. 前端JS配置:
    $.ajax({
    	type: "POST",
    	url: "https://xxx.com/form/list",
    	data: { account: "111", password: "222222" },
     headers:{'Content-Type':'application/json;charset=utf8','Authorization':'1333333333'},//设置凭证
    	dataType: 'json',
    	crossDomain:true,//开启跨域
    	xhrFields: {
    		withCredentials: true //允许跨域带Cookie
    	},
    	success: function(data) {
    		console.log(data)
    	}
    })
    
  3. 前后端协商凭证header,如事例代码中的Authorization,前后端都得加,少了会报错"Provisional headers are shown"
  4. 以上都设置好之后,还会有有一种错误:

    最后一句话就是提示我们要把cookie中的samesite属性设置为None,另外还有一点就是secure属性还得设置为true才行
  5. $arr_cookie_options = array (
                    'expires' => time() + 60*60*24*30,
                    'path' => '/',
                    'domain' => '.example.com', // leading dot for compatibility or use subdomain
                    'secure' => true,     // or false
                    'httponly' => true,    // or false
                    'samesite' => 'None' // None || Lax  || Strict
                    );
    setcookie('TestCookie', 'The Cookie Value', $arr_cookie_options); 

经过这样的设置,应该就没什么问题了