前言
本文主要介绍服务端设置跨域的方式。
正文
1、首先看一下在没有设置允许跨域的时候,从A站点请求B站点的数据,会被浏览器拦截。
2、服务端设置允许跨域
- B站点的服务端使用lighttpd,修改lightpd配置文件,修改点入下图,然后重启lighttpd服务
setenv.add-response-header += ("Access-Control-Allow-Origin" => "*","Access-Control-Allow-Headers" => "*")
3、查看效果
4、引申
当服务端设置允许携带cookie跨域时,即服务器端 Access-Control-Allow-Credentials = true时,参数Access-Control-Allow-Origin 的值不能为 ‘*’ ,必须为具体的域名或IP地址。
设置了具体的域名地址之后,只有指定地址才可访问B站点的设置如下:
$HTTP["url"] =~ "^/api" {
setenv.add-response-header += ( "Cache-Control" => "no-store, no-cache, must-revalidate, post-check=0, pre-check=0" )
setenv.add-response-header += ("Access-Control-Allow-Methods" => "POST, GET, PUT, OPTIONS, DELETE","Access-Control-Allow-Headers" => "Origin, X-Requested-With, Content-Type, Accept, x-token","Access-Control-Allow-Origin" => "https://192.168.143.169","Access-Control-Allow-Credentials" => "true")
}
① A站点可以访问
② C站点不可访问
③跨域携带cookie
访问A站点的时候设置一个cookie,然后从A站点去访问B站点,查看是否会携带A站点的cookie
$HTTP["url"] =~ "^/api" {
setenv.add-response-header += ( "Cache-Control" => "no-store, no-cache, must-revalidate, post-check=0, pre-check=0" )
setenv.add-response-header += ("Access-Control-Allow-Origin" => "*","Set-Cookie" => "userID=testcrossdomain;path=/;httpOnly;secure=true;SameSite=None","Access-Control-Allow-Headers" => "*",
}
通过服务端设置允许携带cookie 之后,实测还是无法生效(即使A站点设置的cookie设置了httpOnly, secure,SameSite=None 依旧不生效)
$.ajax({
url: 'https://192.168.0.86/api/safe_switch',
type: 'get',
xhrFields: {
withCredentials: true,
},
success: function(res) {
console.log("success",res)
},
error: function(err) {
console.log(err)
}
})
5、总结
- IE,chrome ,Firefox 都未携带cookie
- 按照上述设置服务端跨域治藏,IE,chrome可正常进行跨域请求
- Firefox会提示错误跨域请求未成功,根据资料添加证书例外设置之后可成功,设置成功之后服务端设置的"Access-Control-Allow-Origin" => "" 是否是无直接关系,都可访问。
- 如果设置了Access-Control-Allow-Credentials = true,"Access-Control-Allow-Origin" 必须指定具体域名不可设置通配符