ajax跨域产生原因(三个同时满足会产生跨域问题):
1. 浏览器限制
2. 跨域请求了
3. XHR(XMLHttpRequest)请求
解决:
1. 解决浏览器限制:
2.不用XHR请求: 用JsonP(只支持get请求,后端需要修改)
3. 不跨域调用(最后修改的可能都是http服务器,但是不同域的http服务器)
* 被调用方修改,支持跨域(添加返回信息);
* 调用方修改,隐藏跨域
# Filter方案, Nginx
跨域请求,会先看是否是简单请求,非简单请求会先检查后调用
简单请求:
方法为GET, HEAD, POST
请求header里面:
无自定义头;
Content-Type为以下几种: text/plain, multipart/form-data, application/x-www-form-urlencoded
常见的 非简单 请求:
put, delete方法的ajax请求
发送json格式的ajax请求
带自定义头的ajax请求
nginx:
启动: start nginx
nginx -s stop 快速关机
nginx -s quit 优雅的关机
nginx -s reload 更改配置,使用新配置启动新工作进程,正常关闭旧工作进程
nginx -s reopen 重新打开日志文件
查看进程: tasklist /fi "imagename eq nginx.exe"
后台返回值
callbackfunction({"name":"wwwwwwwwwwww"});
@RequestMapping("/gateway/data")
public @ResponseBody String gatewayData(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> result = fundHistoryService.fundsAmountHomePage();
Map<String, Object> map = new HashMap<String, Object>();
map.put("fundInvestsum", ArithmeticUtil.divStrRoundDown(result.get("tradeSum")+"","10000", 0));
map.put("openAccountsum", result.get("openAccountAllsum"));
map.put("companyAccountsum",2718);
JSONObject jsonObject = JSONObject.fromObject(map);
return request.getParameter("callback")+"("+jsonObject.toString()+")";
}
1. 通过script标签引用,写死你需要的src的url地址
<script>
var callbackfunction = function(data) {
console.log('我是跨域请求来的数据-->' + data.name);
};
</script>
<script src="[http://i2.mediapower.mobi/adpower/vm/Bora/js/test.js?callback=callbackfunction](http://i2.mediapower.mobi/adpower/vm/Bora/js/test.js?callback=callbackfunction)"></script>
2. 动态创建script,来调用
function handleResponse(data){
console.log('The responsed data is: '+data);
$('.companyAccountsum').html(data.companyAccountsum);
$('.fundInvestsum').html(data.fundInvestsum);
}
var script = document.createElement('script');
//script.src = 'http://127.0.0.1:8081/yilucaifu/org/gateway/data.html?callback=handleResponse';
script.src = 'https://www.yilucaifu.com/org/gateway/data.html?callback=handleResponse';
document.body.insertBefore(script, document.body.firstChild);
3. JQuery的ajax,get方式
$(function(){
$.ajax({
async: false,
type: "GET",
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'callbackfunction',
url: "http://i2.mediapower.mobi/adpower/vm/Bora/js/test.js",
data: "",
timeout: 3000,
contentType: "application/json;utf-8",
success: function(msg) {
console.log(msg);
}
});
})
$.getJSON(url + "?callback=?", data, function(data) {
}
4. web sockets
web sockets是一种浏览器的API,它的目标是在一个单独的持久连接上提供全双工、双向通信。(同源策略对web sockets不适用)
web sockets原理:在JS创建了web socket之后,会有一个HTTP请求发送到浏览器以发起连接。取得服务器响应后,建立的连接会使用HTTP升级从HTTP协议交换为web sockt协议。
只有在支持web socket协议的服务器上才能正常工作。
var socket = new WebSockt('ws://www.baidu.com');//http->ws; https->wss
socket.send('hello WebSockt');
socket.onmessage = function(event){
var data = event.data;
}
//Spring注解
@CrossOrigin
//过滤器
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletResponse res = (HttpServletResponse) response;
HttpServletRequest req = (HttpServletRequest) request;
String origin = req.getHeader("Origin");
if(!StringUtils.isEmpty(origin)) {
res.addHeader("Access-Control-Allow-Origin", origin);//带cookie这里不能用*
}
res.addHeader("Access-Control-Allow-Methods", "*");
String headers = req.getHeader("Access-Control-Request-Headers");
if(!StringUtils.isEmpty(headers)) {//这里是可以直接写*的
res.addHeader("Access-Control-Allow-Headers", headers);//发送json参数请求
}
res.addHeader("Access-Control-Max-Age", "3600");//预检命令缓存时间 秒
res.addHeader("Access-Control-Allow-Credentials", "true");//带cookie
chain.doFilter(request, response);
}
//前端代理 webpack.dev.config.js
config.devServer = {
noInfo: true,
hot: true,
inline: true,
outputPath: path.join(__dirname, 'dist'),
proxy: {
'/ma-contract': {
target: 'http://127.0.0.1:9999',
secure: false,
changeOrigin: true,
host: '127.0.0.1'
}
}
//Nginx代理
server{
listen 80;
server_name a.com;
location / {
proxy_pass http://localhost:8081;
}
location /ajaxserver{
proxy_pass http://localhost:8080/ajax;
}
}
server{
listen 80;
server_name b.com;
location /{
proxy_pass http://localhost:8080;
add_header Access-Control-Allow-Methods *;
add_header Access-Control-Max-Age 3600;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Origin $http_origin;
add_header Access-Control-Allow-Headers $http_access_control_request_headers;
if ($request_method = OPTIONS){
return 200;
}
}
}
//前端Ajax请求
/* $.ajax({
url : base + "/get1",
type: "get",
dataType : "jsonp",
success:function(json){
console.log(json);
}
}); */
/* $.ajax({//贵金所省份跨域请求
url : "https://mibaoapi.hseb.com.cn/bankbranch/getProveniences.json",
type: "get",
dataType : "jsonp",
success:function(json){
console.log(json);
}
}); */
$.getJSON(base+"/get1").then(function(result){//简单请求
console.log(result);
});
$.ajax({//json格式请求
url : base + "/postJson",
type: "post",
contentType:"application/json;charset=utf-8",
data:JSON.stringify({name:"jack"}),
success:function(json){
console.log(json);
}
});
$.ajax({//带cookie的请求, 浏览器添加cookie: document.cookie = "jsession=jack"
url : base + "/getCookie",
type: "get",
xhrFields:{
withCredentials:true
},
success:function(json){
console.log(json);
}
});
$.ajax({//带自定义头
url : base + "/getHeader",
type: "get",
headers:{
"header1":"jack1"
},
beforeSend:function(xhr){
xhr.setRequestHeader("header2","rose")
},
success:function(json){
console.log(json);
}
});