ajax——CORS跨域调用REST API 的常见问题以及前后端的设置

RESTful架构是目前比较流行的一种互联网软件架构,在此架构之下的浏览器前端和手机端能共用后端接口。

但是涉及到js跨域调用接口总是很头疼,下边就跟着chrome的报错信息一起来解决一下。

假设:前端域名为front.ls-la.me,后端域名为api.ls-la.com。前端需要访问的接口为http://api.ls-la.com/user/info.json,需要用GET方式访问。

现在,用Ajax向后端发送请求,得到第一个错误。(cors跨域的写法参考:http://blog.csdn.net/fdipzone/article/details/46390573)

错误1:

XMLHttpRequest cannot load http://api.ls-la.com/user/info.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://api.ls-la.com' is therefore not allowed access.

提示响应头没有Access-Control-Allow-Origin这一项,谷歌得知需要在服务器指定哪些域名可以访问后端接口,设定之:

header('Access-Control-Allow-Origin: http://front.ls-la.me');
// 如果你不怕扣工资可以这么设:header('Access-Control-Allow-Origin: *');

再次发送请求,又报错。

错误2:

XMLHttpRequest cannot load http://api.ls-la.com/user/info.json. Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers in preflight response.

意思是ajax头信息中有X-Requested-With这一字段,后端不允许。那就让允许吧:

header('Access-Control-Allow-Headers: X-Requested-With');

好了,这下不报错了,但是仔细分析请求过程,发现浏览器向接口地址发送了两个请求,第一个是OPTIONS方式,第二个才是GET方式。

这里的第一个请求叫做“Preflight Table Request(预检表请求,微软这么翻译的,不知道对不对)”。这个请求是在跨域的时候浏览器自行发起的,作用就是先请求一下看看服务器支不支持当前的访问。如果不支持,就会报之前所列的错误;如果支持,再发送正常的GET请求,返回相应的数据。

但是每个请求之前都要这么OPTIONS一下,作为典型处女座表示非常不能忍。需要告诉浏览器你搞一下是个意思,老这么搞就没意思了:

// 告诉浏览器我支持这些方法(后端不支持的方法可以从这里移除,当然你也可以在后边加上OPTIONS方法。。。)
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE');
// 告诉浏览器我已经记得你了,一天之内不要再发送OPTIONS请求了
header('Access-Control-Max-Age: ' . 3600 * 24);

好了,事情至此告一段落。

才怪!

突然有一天测试妹子跑来跟你说网站记不住用户的状态,一检查发现跨域的时候cookie失效了。

错误3:

js在发送跨域请求的时候请求头里默认是不带cookie的,需要让他带上:

 1 // js
 2 var xhr = new XMLHttpRequest();
 3 xhr.open('GET', 'http://api.ls-la.com/user/info.json');
 4 xhr.withCredentials = true;
 5 xhr.onload = onLoadHandler;
 6 xhr.send();
 7 
 8 // jQuery
 9 $.ajax({
10     url: 'http://api.ls-la.com/user/info.json',
11     xhrFields: {
12         withCredentials: true
13     },
14     crossDomain: true,
15 });
16 
17 // Angular 三选一
18 $http.post(url, {withCredentials: true, ...})
19 $http({withCredentials: true, ...}).post(...)
20 app.config(function ($httpProvider) {
21     $httpProvider.defaults.withCredentials = true;
22 }

总之就是要在xhr里设置一下withCredentials = true,然后跨域请求就能带上cookie了。注意这里的cookie遵循同源策略,也就是后端发送的cookie也是属于域名api.ls-la.com的。

发送一个带cookie的post请求,依旧报错:

错误4:

XMLHttpRequest cannot load http://api.ls-la.com/user/info.json. Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

跟上边那个X-Requested-With报错一样,头信息不允许,后端改下:

header('Access-Control-Allow-Headers: X-Requested-With, Content-Type');

再来,还是报错:

错误5:

XMLHttpRequest cannot load http://api.ls-la.com/user/info.json. Response to preflight request doesn't pass access control check: Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin 'http://front.ls-la.me' is therefore not allowed access.

提示很明显,后端代码加一行,允许携带cookie访问:

// 允许前端带cookie访问
header('Access-Control-Allow-Credentials: true');

总结

在后端程序加载前执行以下函数,避免OPTIONS请求浪费系统资源和数据库资源。

function cors_options()
{
    header('Access-Control-Allow-Origin: http://front.ls-la.me');
    header('Access-Control-Allow-Credentials: true');

    if('OPTIONS' != $_SERVER['REQUEST_METHOD']) return;

    header('Access-Control-Allow-Headers: X-Requested-With, Content-Type');
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE');
    header('Access-Control-Max-Age: ' . 3600 * 24);

    exit;
}
原文地址:https://www.cnblogs.com/niejunchan/p/7728333.html