1.CORS
CORS是现代浏览器支持跨域资源请求的一种方式,全称是”跨域资源共享”(Cross-origin resource sharing),当使用XMLHttpRequest发送请求时,浏览器发现该请求不符合同源策略,会给该请求加一个请求头:Origin,后台进行一系列处理,如果确定接受请求则在返回结果中加入一个响应头:Access-Control-Allow-Origin;浏览器判断该相应头中是否包含Origin的值,如果有则浏览器会处理响应,我们就可以拿到响应数据,如果不包含浏览器直接驳回,这时我们无法拿到响应数据。
(1)基本方式
1.在控制层设置
response.setHeader("Access-Control-Allow-Origin", "http://localhost:9105");response.setHeader("Access-Control-Allow-Credentials", "true");
如果是允许所有的域访问可以使用:
response.setHeader("Access-Control-Allow-Origin", "*");
如果是想让请求操作coolie:
response.setHeader("Access-Control-Allow-Credentials", "true");
注意:
如果是设置cookie就不能使用,使用就不能设置cookie
2.前端js
$http.get('http://localhost:9107/cart/addGoodsToCartList.do?itemId='+ $scope.sku.id+'&num='+$scope.num,{'withCredentials':true}).success();
注意:
如果想操作cookie必须设置头信息:{‘withCredentials’:true}
(2) SpringMVC4.2+ 方式注解
在控制层方法上设置注解
@CrossOrigin(origins="http://localhost:9105",allowCredentials="true")
allowCredentials可以省略,默认为true
2.jsonp
JSONP是利用浏览器对script的资源引用没有同源限制,通过动态插入一个script标签,当资源加载到页面后会立即执行的原理实现跨域的。JSONP是一种非正式传输协议,该协议的一个要点就是允许用户传递一个callback或者开始就定义一个回调方法,参数给服务端,然后服务端返回数据时会将这个callback参数作为函数名来包裹住JSON数据,这样客户端就可以随意定制自己的函数来自动处理返回数据了。<br /> JSONP只支持GET请求而不支持POST等其它类型的HTTP请求,它只支持跨域HTTP请求这种情况,不能解决不同域的两个页面之间如何进行JavaScript调用的问题,JSONP的优势在于支持老式浏览器,弊端也比较明显:需要客户端和服务端定制进行开发,服务端返回的数据不能是标准的Json数据,而是callback包裹的数据。
前端代码:
function jsonpTest1() {//传统支持jsonp的方案$.ajax({url: 'http://localhost:8081/jsonp_demo2/jsonp/test1.do',dataType: 'jsonp',success: function (res, status, xhr) {alert(status);alert(res.msg);}});}function jsonpTest2() {//使用MappingJacksonValue,从spring4.1以后版本才可以使用$.ajax({url: 'http://localhost:8081/jsonp_demo2/jsonp/test2.do',dataType: 'jsonp',success: function (res, status, xhr) {alert(status);var resJson = $.parseJSON(res);alert(resJson.msg);}});}
后端代码:
package com.itcast.controller;import org.apache.commons.lang3.StringUtils;import org.springframework.http.converter.json.MappingJacksonValue;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.http.MediaType;/*** JS跨域解决方案一* 描述:JSONP跨域请求controller* @author zhuan* @version 2018年3月31日 上午9:58:50*/@RestController@RequestMapping("/jsonp")public class JsonpController{/**** 描述:传统支持jsonp的方案* @param param* @param callback* @return*/@RequestMapping(value = "/test1", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8")public String jsonTest1(String param, String callback) {if (StringUtils.isNotBlank(callback)) {// 客户端为jsonp请求。需要返回js代码String jsonResutl = callback + "({\"type\":\"json\",\"msg\":\"test1 jsonp request success\"})";return jsonResutl;}return "{\"type\":\"json\",\"msg\":\"test1 json request success\"}";}/**** 描述:从spring4.1以后版本才可以使用** @param param* @param callback* @return*/@RequestMapping("/test2")public Object jsonTest2(String param,String callback){if(StringUtils.isNotBlank(callback)){MappingJacksonValue mappingJacksonValue = new MappingJacksonValue("{\"type\":\"jsonp\",\"msg\":\"test2 jsonp request success\"}");//设置回调方法mappingJacksonValue.setJsonpFunction(callback);return mappingJacksonValue;}return "{\"type\":\"json\",\"msg\":\"test2 json request success\"}";}}
3.VUE解决跨域请求方案
代理
测试 上边的代理 ,结果 报错如下 :
No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin
‘http://localhost:11000‘ is therefore not allowed access.
原因:浏览器的同源策略不允许跨域访问,所谓同源策略是指协议、域名、端口相同。
解决:采用proxyTable解决。
proxyTable是什么?
vue-cli提供的解决vue开发环境下跨域问题的方法,proxyTable的底层使用了http-proxy-
middleware(https://github.com/chimurai/http-proxy-middleware),它是 http代理中间件,它依赖node.js,
基本原理是用服务端代理解决浏览器跨域:
cms跨域解决原理:
1、访问页面http://localhost:11000/
2 、页面请求http://localhost:11000/cms
由于 url由http://localhost:31001/cms...改为 “http://localhost:11000/cms.” ,所以不存在跨域
3、通过proxyTable由node服务器代理请求 http://localhost:31001/cms.
1)修改api方法中url的定义
请求前加/api前缀
//public是对axios的工具类封装,定义了http请求方法import http from './../../../base/api/public'let sysConfig = require('@/../config/sysConfig')let apiUrl = sysConfig.xcApiUrlPre;export const page_list = (page,size,params) => {return http.requestQuickGet(apiUrl+'/cms/page/list/'+page+'/'+size)}
2)在config/index.js下配置proxyTable。
以/api/cms开头的请求,代理请求http://localhost:31001
'/api/cms': {target: 'http://localhost:31001',pathRewrite: {'^/api': ''//实际请求去掉/api}
