前端常见跨域解决方案(全)
1.)资源跳转:A链接、重定向、表单提交 2.)资源嵌入:、
onBack({"status":true,"user":"admin"})
$.ajax({
url:'http://www.domain2.com:8080/login',
type:'get',
dataType:'jsonp',//请求方式为jsonp
jsonpCallback:"onBack",//自定义回调函数名
data:{}
});
this.$http.jsonp('http://www.domain2.com:8080/login',{
params:{},
jsonp:'onBack'
}).then((res)=>{
console.log(res);
})
varquerystring=require('querystring');
varhttp=require('http');
varserver=http.createServer();
server.on('request',function(req,res){
varparams=qs.parse(req.url.split('?')[1]);
varfn=params.callback;
//jsonp返回设置
res.writeHead(200,{'Content-Type':'text/javascript'});
res.write(fn+'('+JSON.stringify(params)+')');
res.end();
});
server.listen('8080');
console.log('Serverisrunningatport8080...');
varproxy=function(url,callback){
varstate=0;
variframe=document.createElement('iframe');
//加载跨域页面
iframe.src=url;
//onload事件会触发2次,第1次加载跨域页,并留存数据于window.name
iframe.onload=function(){
if(state===1){
//第2次onload(同域proxy页)成功后,读取同域window.name中数据
callback(iframe.contentWindow.name);
destoryFrame();
}elseif(state===0){
//第1次onload(跨域页)成功后,切换到同域代理页面
iframe.contentWindow.location='http://www.domain1.com/proxy.html';
state=1;
}
};
document.body.appendChild(iframe);
//获取数据以后销毁这个iframe,释放内存;这也保证了安全(不被其他域framejs访问)
functiondestoryFrame(){
iframe.contentWindow.document.write('');
iframe.contentWindow.close();
document.body.removeChild(iframe);
}
};
//请求跨域b页面数据
proxy('http://www.domain2.com/b.html',function(data){
alert(data);
});
中间代理页,与a.html同域,内容为空即可。
//前端设置是否带cookie xhr.withCredentials=true;
varxhr=newXMLHttpRequest();//IE8/9需用window.XDomainRequest兼容
//前端设置是否带cookie
xhr.withCredentials=true;
xhr.open('post','http://www.domain2.com:8080/login',true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send('user=admin');
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
alert(xhr.responseText);
}
};
$.ajax({
...
xhrFields:{
withCredentials:true//前端设置是否带cookie
},
crossDomain:true,//会让请求头中包含跨域的额外信息,但不会含cookie
...
});
Vue.http.options.credentials=true
/*
*导入包:importjavax.servlet.http.HttpServletResponse;
*接口参数中定义:HttpServletResponseresponse
*/
response.setHeader("Access-Control-Allow-Origin","http://www.domain1.com");//若有端口需写全(协议+域名+端口)
response.setHeader("Access-Control-Allow-Credentials","true");
varhttp=require('http');
varserver=http.createServer();
varqs=require('querystring');
server.on('request',function(req,res){
varpostData='';
//数据块接收中
req.addListener('data',function(chunk){
postData+=chunk;
});
//数据接收完毕
req.addListener('end',function(){
postData=qs.parse(postData);
//跨域后台设置
res.writeHead(200,{
'Access-Control-Allow-Credentials':'true',//后端允许发送Cookie
'Access-Control-Allow-Origin':'http://www.domain1.com',//允许访问的域(协议+域名+端口)
'Set-Cookie':'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly'//HttpOnly:脚本无法读取cookie
});
res.write(JSON.stringify(postData));
res.end();
});
});
server.listen('8080');
console.log('Serverisrunningatport8080...');
location/{
add_headerAccess-Control-Allow-Origin*;
}
#proxy服务器
server{
listen81;
server_namewww.domain1.com;
location/{
proxy_passhttp://www.domain2.com:8080;#反向代理
proxy_cookie_domainwww.domain2.comwww.domain1.com;#修改cookie里域名
indexindex.htmlindex.htm;
#当用webpack-dev-server等中间件代理接口访问nignx时,此时无浏览器参与,故没有同源限制,下面的跨域配置可不启用
add_headerAccess-Control-Allow-Originhttp://www.domain1.com;#当前端只跨域不带cookie时,可为*
add_headerAccess-Control-Allow-Credentialstrue;
}
}
varxhr=newXMLHttpRequest();
//前端开关:浏览器是否读写cookie
xhr.withCredentials=true;
//访问nginx中的代理服务器
xhr.open('get','http://www.domain1.com:81/?user=admin',true);
xhr.send();
varhttp=require('http');
varserver=http.createServer();
varqs=require('querystring');
server.on('request',function(req,res){
varparams=qs.parse(req.url.substring(2));
//向前台写cookie
res.writeHead(200,{
'Set-Cookie':'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly'//HttpOnly:脚本无法读取
});
res.write(JSON.stringify(params));
res.end();
});
server.listen('8080');
console.log('Serverisrunningatport8080...');
varxhr=newXMLHttpRequest();
//前端开关:浏览器是否读写cookie
xhr.withCredentials=true;
//访问http-proxy-middleware代理服务器
xhr.open('get','http://www.domain1.com:3000/login?user=admin',true);
xhr.send();
varexpress=require('express');
varproxy=require('http-proxy-middleware');
varapp=express();
app.use('/',proxy({
//代理跨域目标接口
target:'http://www.domain2.com:8080',
changeOrigin:true,
//修改响应头信息,实现跨域并允许带cookie
onProxyRes:function(proxyRes,req,res){
res.header('Access-Control-Allow-Origin','http://www.domain1.com');
res.header('Access-Control-Allow-Credentials','true');
},
//修改响应信息中的cookie域名
cookieDomainRewrite:'www.domain1.com'//可以为false,表示不修改
}));
app.listen(3000);
console.log('Proxyserverislistenatport3000...');
module.exports={
entry:{},
module:{},
...
devServer:{
historyApiFallback:true,
proxy:[{
context:'/login',
target:'http://www.domain2.com:8080',//代理跨域目标接口
changeOrigin:true,
cookieDomainRewrite:'www.domain1.com'//可以为false,表示不修改
}],
noInfo:true
}
}
userinput:
varhttp=require('http');
varsocket=require('socket.io');
//启http服务
varserver=http.createServer(function(req,res){
res.writeHead(200,{
'Content-type':'text/html'
});
res.end();
});
server.listen('8080');
console.log('Serverisrunningatport8080...');
//监听socket连接
socket.listen(server).on('connection',function(client){
//接收信息
client.on('message',function(msg){
client.send('hello:'+msg);
console.log('datafromclient:--->'+msg);
});
//断开处理
client.on('disconnect',function(){
console.log('Clientsockethasclosed.');
});
});
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。