跨域以及解决跨域的方式
跨域的产生
跨域是记基于同源策略产生的,他是浏览器最基本的安全也是最可靠的安全措施,跨域是指在请求一个url的时候与当前页面的url的 域名,协议名,端口号之中有一个不同就 会产生跨域,
解决跨域
解决跨域问题有很多方法比较常用的方式有 jsonp,cors,代理服务器
jsonp
jsonp解决跨域流传于民间高手利用script标签解决跨域问题详情如下
首先创建一个script标签
let script= document.creataElent(`script`);
然后利用script中的src来设置你请求到的url地址代码如下
script.setAttribute(`src`,`http//127.0.0.1:3000/stu`)
**(setAttribute() 方法添加指定的属性,并为其赋指定的值。)**
最后将创建的script赋值到页面的头部
document.getElementsByTagName(`head`)[0].appendchild(script)
服务器端的修改(表现层)
res.send(`console.log([
{name : '小明',age : 18},
{name : 't叮当猫',age : 20}
])`);
});
在jqurey中用jsop解决方式
$.ajax({
url : 'http://127.0.0.1:3000/stu?callback=?',
dataType : 'jsonp',
success : function(data){
console.log(data);
}
})
router.get('/', async function(req, res, next) {
// 在服务器端,所有要拿到 jquery 生成的函数
const func = url.parse(req.url,true).query.callback;
res.send(`${func}([
{name : 'xiaoming'},{name: 'aaa'}
])`);
});
cors
cors解决跨域(只需要在请求头里添加一些数据即可)创建一个中间件,这个中间件可以往响应头里面添加键值对
function allowCrossOrigin(req,res,next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With,Origin,Content-Type,Accept");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header('Access-Control-Allow-Credentials','true');
next();
}
// 注册中间件
app.use(allowCrossOrigin)
代理服务器
因为服务器不存在同源策略所以我们可以用代理服务器解决跨域
使用中间件http-proxy-middleware
在代理服务器的app.js文件做如下配置
const options = {
target : 'http://127.0.0.1:3001', // 你要进行转发,转发到哪里去
changeOrigin : true, // 允许跨域
// URL 的改写规则
pathRewrite : {
'^/api' : '/'
// 这里意味 URL 里面有 api 的就是要改写,并且要转发的
// http://localhost:3000/api/stu
// 就会被改写为 http://127.0.0.1:3001/stu
}
}
app.use('/api',proxy.createProxyMiddleware(options));
发送请求的时候在请求url首位添加/api即可
$.ajax({
url: 'http://localhost:3000/api/stu',
type: 'GET',
success: function (data) {
console.log(data);
}
})