前端跨域请求如何实现?

已邀请:

zkbhj - 凯冰科技站长

赞同来自:

原生ajax请求方式:
var xhr = new XMLHttpRequest();  
xhr.open("POST", "http://xxxx.com/demo/b/index.php", true);
xhr.withCredentials = true; //支持跨域发送cookies
xhr.send();







jquery的ajax的post方法请求:
$.ajax({
type: "POST",
url: "http://xxx.com/api/test",
dataType: 'json',
xhrFields: {
withCredentials: true
},
crossDomain: true,
success:function(){
},
error:function(){
}
})

服务器端设置:
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: http://www.xxx.com";);
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Origin 'http://192.168.0.1:8080';
#注意这两个设置项当第一个为true时,第二个不能设置为*,否则前端访问会报错,必须制定具体域名url
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';

Access-Control-Allow-Credentials : 该字段可选。它的值是一个布尔值,表示是否允许发送Cookie。默认情况下,Cookie不包括在CORS请求之中。设为true,即表示服务器明确许可,Cookie可以包含在请求中,一起发给服务器。这个值也只能设为true,如果服务器不要浏览器发送Cookie,删除该字段即可。

Yii2框架:
/**
* @inheritdoc
*/
public function behaviors()
{

return [

'corsFilter' => [
'class' => \yii\filters\Cors::className(),
'cors' => [
'Origin' => ['*'],
'Access-Control-Allow-Credentials' => true,
]
],
];
}
 
具体详细信息,请参考:https://developer.mozilla.org/ ... ntrol

要回复问题请先登录注册