以下原文链接:https://www.cnblogs.com/woodk/p/5578448.html
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.youkuaiyun.com/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的,需要让他带上:
// js
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://api.ls-la.com/user/info.json');
xhr.withCredentials = true;
xhr.onload = onLoadHandler;
xhr.send();
// jQuery
$.ajax({
url: 'http://api.ls-la.com/user/info.json',
xhrFields: {
withCredentials: true
},
crossDomain: true,
});
// Angular 三选一
$http.post(url, {withCredentials: true, ...})
$http({withCredentials: true, ...}).post(...)
app.config(function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
}
总之就是要在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.jianshu.com/p/26f877d2b315
开篇
因为CORS的出现,大大降低了跨域的难度,另到AJAX有了更大的发挥空间,也导致了前后端更加容易实现。但是今天在实现前后端的时候发现了一个问题。在进行session会话管理的时候,前端无法发送cookie到后端,前端每次访问后端都相当于一次新的会话,这样就导致登录后的信息是无法保存的。客户端每一次访问都需要重新登录。
原因
对于前端来说,seesion字段是存在cookie中的。在跨域过程中,Cookie是默认不发送的。就算后端返回set-Cookie字段,前端也不会保存Cookie,更不会在下一次访问的时候发送到后端了。
因此只要前端可以把cookie发送到后端,后端就可以根据cookie拿到seeion字段进行会话验证。
进过重新对CORS的学习,只要通过3步,就可以让会话保持。
第一步
在ajax中设置,withCredentials: true。
例如:
$.ajax({
url: a_cross_domain_url,
xhrFields: {
withCredentials: true
}
});
默认情况下,跨源请求不提供凭据(cookie、HTTP认证及客户端SSL证明等)。通过将withCredentials属性设置为true,可以指定某个请求应该发送凭据。
第二步
服务端的Access-Control-Allow-Origin 不可以设置为"*",必须指定明确的、与请求网页一致的域名
第三步
服务端的 Access-Control-Allow-Credentials: true,代表服务器接受Cookie和HTTP认证信息。因为在CORS下,是默认不接受的。
PS:
在spring boot 中,可以写一个配置类来实现
@Configuration
public class CORSConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedHeaders("*")
.allowedMethods("*")
.allowCredentials(true);
}
};
}
}
在SSM中可以写一个Filter实现。
public class AjaxFilter extends OncePerRequestFilter{
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, If-Modified-Since");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.addHeader("Access-Control-Allow-Credentials", "true");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
//此行代码确保请求可以继续执行至Controller
filterChain.doFilter(request, response);
}
}
web.xml
<filter>
<filter-name>ajaxFilter</filter-name>
<filter-class>xxxx.AjaxFilter</filter-class><!-- 自定义过滤器 -->
</filter>
<filter-mapping>
<filter-name>ajaxFilter</filter-name>
<url-pattern>/*</url-pattern>