1. ajax跨域请求(无cookie、无header)案例(java)
(1)启动一个java web项目,配置两个域名(host),czt.ming.com、czt.casicloud.com,java后端代码如下:
注意:access-control-allow-origin
/**
*
* @title: getajaxcross
* @description: todo(ajax请求,跨域)
* @param request
* @param response
*/
@requestmapping(value ="/getajaxcross",method= {requestmethod.get})
public void getajaxcross(httpservletrequest request, httpservletresponse response){
try {
response.setcharacterencoding("utf-8");
//设置允许多个域名允许跨域集合
string[] allowdomains = {"http://czt.casicloud.com", "http://czt.ming.com"};
set alloworigins = new hashset(arrays.aslist(allowdomains));
string origin = request.getheader("origin");
if(alloworigins.contains(origin)){
//设置允许跨域的配置:access-control-allow-origin: 响应头指定了该响应的资源是否被允许与给定的origin共享
response.setheader("access-control-allow-origin", origin);
}
//数据
map<string, object> resultmap = new hashmap<string, object>();
resultmap.put("message", "ajax请求,跨域成功");
string result = jsonutils.objecttojson(resultmap);
response.getwriter().write(result);
} catch (exception e) {
e.printstacktrace();
}
}(2)前端页面代码如下:
//4.ajax跨域
function getcookieajaxcross() {
$.ajax({
type:"get",
url:"http://czt.ming.com/xxx/xxx/xxx/getajaxcross",
async:true,
data:{},
datatype: 'json',
success: function(data) {
console.log(data);
}
});
}
getcookieajaxcross();(3)测试ajax跨域请求:
通过http://czt.casicloud.com/xxx/xxx访问页面,js触发ajax跨域请求http://czt.ming.com/xxx/xxx/xxx/getajaxcross,前端和后台如果不按照代码中配置相应参数会报各种跨域错误;
2. ajax跨域请求获取和创建cookie案例(java)
(1)启动一个java web项目,配置两个域名(host),czt.ming.com、czt.casicloud.com,java后端代码如下:
注意:access-control-allow-credentials和access-control-allow-origin
/**
*
* @title: getcookieajax
* @description: todo(ajax请求,跨域传递cookie)
* @param request
* @param response
*/
@requestmapping(value ="/getcookieajax",method= {requestmethod.get})
public void getcookieajax(httpservletrequest request, httpservletresponse response){
try {
response.setcharacterencoding("utf-8");
response.setheader("access-control-allow-credentials", "true");
//设置允许多个域名允许跨域集合
string[] allowdomains = {"http://czt.casicloud.com", "http://czt.ming.com"};
set alloworigins = new hashset(arrays.aslist(allowdomains));
string origin = request.getheader("origin");
if(alloworigins.contains(origin)){
//设置允许跨域的配置:access-control-allow-origin: 响应头指定了该响应的资源是否被允许与给定的origin共享
response.setheader("access-control-allow-origin", origin);
}
//获取cookie
cookie[] cookies = request.getcookies();
//设置cookie
cookie cookie = new cookie("access_token_ajax", uuid.randomuuid().tostring());
cookie.setpath("/");
response.addcookie(cookie);
//数据
map<string, object> resultmap = new hashmap<string, object>();
resultmap.put("cookies", cookies);
resultmap.put("message", "ajax请求,跨域传递cookie成功");
string result = jsonutils.objecttojson(resultmap);
response.getwriter().write(result);
} catch (exception e) {
e.printstacktrace();
}
}(2)前端页面代码如下:
注意:withcredentials和crossdomain(作用不明)
//4.ajax跨域携带cookie和自定义请求头header
function getcookieajaxcross() {
$.ajax({
type:"get",
url:"http://czt.ming.com/industry/api/publishforeign/getcookieajax",
async:true,
data:{},
datatype: 'json',
xhrfields: {
withcredentials: true // 发送ajax时,request header中会带上 cookie 信息。
},
crossdomain: true, // 发送ajax时,request header 中会包含跨域的额外信息,但不会含cookie(作用不明,不会影响请求头的携带)
success: function(data) {
console.log(data);
}
});
}
getcookieajaxcross();(3)测试ajax跨域请求获取和创建cookie:
通过http://czt.casicloud.com/xxx/xxx访问页面,js触发ajax跨域请求http://czt.ming.com/xxx/xxx/xxxx/getcookieajax,前端和后台如果不按照代码中配置相应参数会报各种跨域错误;
3. ajax跨域请求,携带请求头header案例(java)
(1)启动一个java web项目,配置两个域名(host),czt.ming.com、czt.casicloud.com;
(2)ajax跨域携带请求头会发送两次请求,一次预检查请求(options),预检查请求通过之后才会进行真正的请求,所以java后台需要配置相应的跨域过滤器,如下:
import java.io.ioexception;
import java.util.arrays;
import java.util.hashset;
import java.util.set;
import javax.servlet.filter;
import javax.servlet.filterchain;
import javax.servlet.filterconfig;
import javax.servlet.servletexception;
import javax.servlet.servletrequest;
import javax.servlet.servletresponse;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
/**
*
* @classname: corsfilter
* @description: todo(跨域请求过滤器)
* @author clm
* @date 2019年10月25日
*
*/
public class corsfilter implements filter {
@override
public void dofilter(servletrequest servletrequest, servletresponse servletresponse, filterchain filterchain)
throws ioexception, servletexception {
/*
* 跨域请求头服务端配置:
* 1.access-control-allow-origin:设置允许跨域的配置, 响应头指定了该响应的资源是否被允许与给定的origin共享
* 2.access-control-allow-credentials:响应头表示是否可以将对请求的响应暴露给页面(cookie)。返回true则可以,其他值均不可以。
* 3.access-control-allow-headers:用于预检请求中,列出了将会在正式请求的 access-control-request-headers 字段中出现的首部信息。(自定义请求头)
* 4.access-control-allow-methods:在对 预检请求的应答中明确了客户端所要访问的资源允许使用的方法或方法列表。
*/
httpservletrequest httprequest = (httpservletrequest) servletrequest;
httpservletresponse httpresponse = (httpservletresponse) servletresponse;
//设置允许多个域名允许跨域集合
string[] allowdomains = {"http://czt.casicloud.com", "http://czt.ming.com"};
set<string> alloworigins = new hashset<string>(arrays.aslist(allowdomains));
string origin = httprequest.getheader("origin");
if(alloworigins.contains(origin)){
//设置允许跨域的配置:access-control-allow-origin: 响应头指定了该响应的资源是否被允许与给定的origin共享
httpresponse.setheader("access-control-allow-origin", origin);
}
httpresponse.setheader("access-control-allow-credentials", "true");
httpresponse.setheader("access-control-allow-headers",
"origin, x-requested-with, content-type, accept, access-token");
httpresponse.setheader("access-control-allow-methods", "get, put, delete, post, options");
if (httprequest.getmethod().equalsignorecase("options")) {
httpresponse.setstatus(202);
httpresponse.getwriter().close();
return;
}
filterchain.dofilter(servletrequest, servletresponse);
}
@override
public void destroy() {
}
@override
public void init(filterconfig filterconfig) throws servletexception {
}
}
web.xml中配置过滤器:
<filter>
<filter-name>corsfilter</filter-name>
<filter-class>xxx.xxx.xxx.xx.xxx.corsfilter</filter-class>
</filter>
<filter-mapping>
<filter-name>corsfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>(3)java后台controller代码:
/**
*
* @title: getpersonheader
* @description: todo(跨域获取请求头)
* @param request
* @param response
*/
@requestmapping(value ="/getpersonheader",method=requestmethod.get)
public void getpersonheader(httpservletrequest request, httpservletresponse response){
try {
response.setcharacterencoding("utf-8");
string personheader = request.getheader("access-token");
system.err.println("获取自定义请求头(access-token):" + personheader);
//数据
map<string, object> resultmap = new hashmap<string, object>();
resultmap.put("message", "跨域获取请求头成功");
resultmap.put("personheader", personheader);
string result = jsonutils.objecttojson(resultmap);
response.getwriter().write(result);
} catch (exception e) {
e.printstacktrace();
}
}(4)前端页面代码如下:
//同域前端设置自定义请求头,后端获取自定义请求头
function getpersonheader() {
$.ajax({
type:"get",
url:"/xxx/xxx/xxx/getpersonheader",
async:true,
//ajax配置请求头方式,第一种
headers: {
"access-token":"access-token123456",//自定义请求头
"content-type":"application/json;charset=utf8"
},
//ajax配置请求头方式,第二种
//beforesend : function(request) {
// request.setrequestheader("access-token", "access-token123456");
// request.setrequestheader("content-type", "application/json;charset=utf8");
//}
data:{},
success: function(data) {
console.log(data);
}
});
}
getpersonheader();
//跨域前端设置自定义请求头,后端获取自定义请求头
function getpersonheadercross() {
$.ajax({
type:"get",
url:"http://czt.ming.com/xxx/xxx/xxx/getpersonheader",
async:true,
headers: {
"access-token":"access-token123456",//自定义请求头
"content-type":"application/json;charset=utf8"
},
data:{},
crossdomain: true, // 发送ajax时,request header 中会包含跨域的额外信息,但不会含cookie(作用不明,不会影响请求头的携带)
success: function(data) {
console.log(data);
}
});
}
getpersonheadercross();(5)测试ajax跨域请求携带请求头header:
通过http://czt.casicloud.com/xxx/xxx访问页面,js触发ajax跨域请求http://czt.ming.com/xxx/xxx/xxxx/getpersonheader,前端和后台如果不按照代码中配置相应参数会报各种跨域错误;
3. jsonp实现跨域读写cookie案例(java)
(1)启动一个java web项目,配置两个域名(host),czt.ming.com、czt.casicloud.com;
(2)java后台jsonp代码:
/**
*
* @title: setcookie
* @description: todo(jsonp跨域设置cookie)
* @param request
* @param response
*/
@requestmapping(value ="/setcookie.jsonp",method=requestmethod.get)
public void setcookie(httpservletrequest request, httpservletresponse response){
try {
response.setcharacterencoding("utf-8");
//设置cookie
cookie cookie = new cookie("access_token", uuid.randomuuid().tostring());
cookie.setpath("/");
response.addcookie(cookie);
//数据
map<string, object> resultmap = new hashmap<string, object>();
resultmap.put("cookie", cookie);
resultmap.put("message", "跨域设置cookie成功");
string result = jsonutils.objecttojson(resultmap);
//前端传过来的回调函数名称
string callback = request.getparameter("callback");
//用回调函数名称包裹返回数据,这样,返回数据就作为回调函数的参数传回去了
result = callback + "(" + result + ")";
response.getwriter().write(result);
} catch (exception e) {
e.printstacktrace();
}
}
/**
*
* @title: getcookie
* @description: todo(jsonp跨域获取cookie)
* @param request
* @param response
*/
@requestmapping(value ="/getcookie.jsonp",method=requestmethod.get)
public void getcookie(httpservletrequest request, httpservletresponse response){
try {
response.setcharacterencoding("utf-8");
//获取cookie
cookie[] cookies = request.getcookies();
//数据
map<string, object> resultmap = new hashmap<string, object>();
resultmap.put("cookies", cookies);
resultmap.put("message", "跨域获取cookie成功");
string result = jsonutils.objecttojson(resultmap);
//前端传过来的回调函数名称
string callback = request.getparameter("callback");
//用回调函数名称包裹返回数据,这样,返回数据就作为回调函数的参数传回去了
result = callback + "(" + result + ")";
response.getwriter().write(result);
} catch (exception e) {
e.printstacktrace();
}
}(3)前端代码:
//1.jsonp跨域设置cookie
function setcookiecrossjsonp() {
$.ajax({
type:"get",
url:"http://czt.ming.com/industry/api/publishforeign/setcookie.jsonp",
async:true,
data:{},
datatype: "jsonp", //返回类型为jsonp,实现跨域
jsonp:"callback", //jsonp和jsonpcallback相当于在url后添加一个参数:?callback=back
jsonpcallback:"back", //设定回调函数的名字,传到后台,进行包装,不设定自动生成
success: function(data) { //成功执行处理,对应后台返回的back(data)方法
console.log(data);
}
});
}
setcookiecrossjsonp();
//2.jsonp跨域获取cookie
function getcookiecrossjsonp() {
$.ajax({
type:"get",
url:"http://czt.ming.com/industry/api/publishforeign/getcookie.jsonp",
async:true,
data:{},
datatype: "jsonp", //返回类型为jsonp,实现跨域
jsonp:"callback", //jsonp和jsonpcallback相当于在url后添加一个参数:?callback=back
jsonpcallback:"back1", //设定回调函数的名字,传到后台,进行包装,不设定自动生成
success: function(data) { //成功执行处理,对应后台返回的back(data)方法
console.log(data);
}
});
}
getcookiecrossjsonp();(4)测试jsonp跨域请求获取和创建cookie:
通过http://czt.casicloud.com/xxx/xxx访问页面,js触发jsonp跨域请求http://czt.ming.com/xxx/xxx/xxxx/getcookie.jsonp、http://czt.ming.com/xxx/xxx/xxxx/setcookie.jsonp,能够正常跨域设置cookie和获取cookie;
ajax请求携带cookie、自定义header总结: 错误:
1.ajax请求时是不会自动带上cookie的,要是想让他带上的话,必须设置withcredential为true。
正确:
1.ajax同域请求下,ajax会自动带上同源的cookie;
2.ajax同域请求下,ajax添加自定义请求头(或原装)header,前端、后台不需要增加任何配置,
并且不会因为增加自定义请求头header,而引起预检查请求(options);
3.ajax跨域请求下,如果不需要携带cookie、请求头header,只需要在后台配置相应参数即可;
后台参数:
(1).access-control-allow-origin:设置允许跨域的配置, 响应头指定了该响应的资源是否被允许与给定的origin共享;
4.ajax跨域请求下,ajax不会自动携带同源的cookie,需要通过前端配置相应参数才可以跨域携带同源cookie,后台配置相应参数才可以跨域返回同源cookie;
前端参数:
withcredentials: true(发送ajax时,request header中会带上cookie信息)
后台参数:
(1).access-control-allow-origin:设置允许跨域的配置, 响应头指定了该响应的资源是否被允许与给定的origin共享;
特别说明:配置了access-control-allow-credentials:true则不能把access-control-allow-origin设置为通配符*;
(2).access-control-allow-credentials:响应头表示是否可以将对请求的响应暴露给页面(cookie)。返回true则可以,其他值均不可以。
5.ajax请求任何时候都不会带上不同源的cookie(cookie遵循同源策略);
6.ajax跨域请求下,ajax添加自定义或者原装的请求头,请求会发送两次,第一次预检查请求,第二次正常请求,详细描述:
post(或get)跨域请求时,分为简单请求和复杂请求,跨域携带自定义或者原装请求头头时是复杂请求。
复杂请求会先发送一个method 为option的请求,目的是试探服务器是否接受发起的请求. 如果服务器说可以,再进行post(或get)请求。
对于java后台web应用,跨域需要添加一个过滤器(过滤器详见下面案例代码),这个过滤器做的事就是,加了几个http header在返回中,
access-control-allow-origin 我能接受的跨域请求来源,配置主机名
access-control-allow-headers 表示能接受的http头部,别忘了加入你自己发明创造的头部
access-control-allow-methods 表示能接受的http mothed ,反正就那几种,全写上也无妨,猥琐点就只写 post, options
如果是option返回空,设置返回码为202,202表示通过。
需要前端配置相应参数才可以跨域携带请求头,后台配置相应参数进行跨域携带请求头;
前端参数:
crossdomain:true(发送ajax时,request header 中会包含跨域的额外信息,但不会含cookie(作用不明,不会影响请求头的携带))
后台参数(配置预检查过滤器):
(1)access-control-allow-origin:设置允许跨域的配置, 响应头指定了该响应的资源是否被允许与给定的origin共享;
(2)access-control-allow-credentials:响应头表示是否可以将对请求的响应暴露给页面(cookie)。返回true则可以,其他值均不可以;
(3)access-control-allow-headers:用于预检请求中,列出了将会在正式请求的 access-control-request-headers 字段中出现的首部信息。(自定义请求头);
(4)access-control-allow-methods:在对预检请求的应答中明确了客户端所要访问的资源允许使用的方法或方法列表;
亲测小结论:
1.ajax跨域请求下,后台不配置跨域access-control-allow-origin,同样能够执行后台方法,但是无法执行ajax的success的方法,控制台报跨域错误;
2.ajax跨域请求下,前端配置withcredentials: false,同样能够执行后台方法,但是无法携带同源cookie,后台无法获取;
3.ajax跨域请求下,前端配置withcredentials: true,后端没有配置access-control-allow-credentials:true,同样能够执行后台方法,并能够生成cookie并返回浏览器,但是无法执行ajax的success的方法,控制台报跨域错误;
4.ajax跨域请求下,前端配置withcredentials: false或不配置withcredentials,后端配置access-control-allow-credentials:true或者false,同样能够执行后台方法,并能够生成cookie并返回浏览器,但是无法携带同源cookie,能够执行ajax的success的方法;
5.cookie携带只区分域名,不区分端口;
6.jsonp可以携带cookie,但只能携带所属域名的cookie(同源策略);
7.jsonp可以跨域生成cookie,流程如下:跨域请求之后,在服务器端生成cookie,并在浏览器端记录相应的cookie;
8.静态资源同样会携带cookie(js和图片等),但是如果是和当前页面不同域只是在network中不显示cookie选项,但是后台能够获取到对应cookie;
9.ajax同域请求会自动带上同源的cookie,不会带上不同源的cookie;
10.这是mdn对withcredentials的解释: mdn-withcredentials ,我接着解释一下同源。
众所周知,ajax请求是有同源策略的,虽然可以应用cors等手段来实现跨域,但是这并不是说这样就是“同源”了。ajax在请求时就会因为这个同源的问题而决定是否带上cookie,这样解释应该没有问题了吧,还不知道同源策略的,应该去谷歌一下看看。
总结:最好前端后台配置跨域,则同时配置相应的跨域配置,否则总会出现不可控的错误;
到此这篇关于ajax请求携带自定义请求头header(跨域和同域)的文章就介绍到这了,更多相关ajax请求携带header内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论