irpas技术客

跨域如此简单_faramita_of_mine

网络 2413

跨域如此简单 一、跨域二、代理三、jsonp四、服务端允许跨域五、携带 cookies 的跨域六、携带自定义头的跨域

一、跨域

??跨域即是当前的 web 应用访问了不属于当前 web 应用的接口资源时,浏览器的对资源的一种保护作用。

Failed to load http://localhost:8080/test: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8020' is therefore not allowed access.

??原因是服务端响应的响应头没有告诉浏览器,该资源不允许被跨域调用。

??跨域是浏览器的一种安全保护机制,后台之间相互调用不存在跨域问题。跨域通常有如下几种解决办法。

二、代理

??vue 开发时有一个这样的配置 config/index.js ,这是使用 node.js 的代理功能。即页面请求还是请求本地,本地有一个代理服务将请求代理到目标服务器上。通过这种方式,把原来的前后台跨域调用变为后台与后台之间的跨域调用,由于跨域报错问题只存在浏览器上,后台调用正常进行,所以问题便被解决。

proxyTable: { '/api': { target:'http://localhost:8080/', changeOrigin: true, pathRewrite: { '^/api': '/' } } }

??在实际开发中,通常也会使用 nginx 的反向代理功能解决跨域问题。

location ^~ / { proxy_pass http://127.0.0.1:8080/; } 三、jsonp

??jsonp 的原理是当前 web 应用可以请求其他 web 应用的 JavaScript 脚本资源,如果我们把数据放在。

$.ajax("http://127.0.0.1:8080/test", { type: "get", dataType: "jsonp", success: function (data) { alert(JSON.stringify(data)) } })

??使用 jsonp 时浏览器会给当前 html 文件创建一个路径为 jsonp 路径的 js 脚本,浏览器就去请求对应的脚本

window.onload = function () { addScriptTag('http:/127.0.0.1:8080/test?callback=foo'); }

??请求到的脚本格式如下

foo({ "test": "testData" });

??数据就包含在一个方法中,jQuery 就能获取到方法中,也就是后台传过来的数据,这种方式是除代理外兼容性最好的解决方案。

四、服务端允许跨域

??满足浏览器跨域要求,即在响应头中加入Access-Control-Allow-Origin

response.setHeader("Access-Control-Allow-Origin", "*");

??响应头如下: ??在 spring mvc 中只需要在控制器类上加一个 @CrossOrigin 注解即可解决。

五、携带 cookies 的跨域

??jQuery 的 ajax 携带 cookies 时,使用参数 xhrFields: { withCredentials: true }表示在跨域请求时带上 cookies 凭证。

$.ajax({ type: "post", url: "http://127.0.0.1:8080/test", xhrFields: { withCredentials: true }, success: function(data) { alert(data) } });

??浏览器报如下错误:

Failed to load http://localhost:8080/test: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://127.0.0.1:8020' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

??大致意思是带 cookies 凭证时Access-Control-Allow-Origin 不能为 *,必须为当前请求的主机,当前的主机在请求头里面有,所以就有。

String origin = request.getHeader("Origin"); response.setHeader("Access-Control-Allow-Origin", origin);

??修改后刷新页面发现还在报错

Failed to load http://localhost:8080/test: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. Origin 'http://127.0.0.1:8020' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

??大致意思是跨域请求携带 cookies 凭证时 Access-Control-Allow-Credentials 必须为 true

response.setHeader("Access-Control-Allow-Credentials", "true");

??请求成功,总配置如下

String origin = request.getHeader("Origin"); response.setHeader("Access-Control-Allow-Origin", origin); response.setHeader("Access-Control-Allow-Credentials", "true"); 六、携带自定义头的跨域

??当有一些特殊需求如请求头加入一些用户数据时,发现跨域又不能用了,而且发请求前会发送一个类型为Request Method:OPTIONS的预检请求

$.ajax({ type: "post", url: "http://localhost:8080/test", headers: { 'userId': '1' }, xhrFields: { withCredentials: true }, async: true, success: function(data) { alert(data) } });

??发现跨域又不能用了

Failed to load http://localhost:8080/test: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8020' is therefore not allowed access. The response had HTTP status code 403.

??原因是预检时请求头不匹配,只需在拦截器或过滤器里面加入如下即可。

String origin = request.getHeader("Origin"); String header = request.getHeader("Access-Control-Request-Headers"); response.addHeader("Access-Control-Allow-Methods", "*"); response.addHeader("Access-Control-Max-Age", "600");//预检请求的结果缓存10分钟 response.addHeader("Access-Control-Allow-Origin", origin); response.addHeader("Access-Control-Allow-Credentials", "true"); response.addHeader("Access-Control-Allow-Headers", header);


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #跨域如此简单 #Cookies #Web #应用访问了不属于当前