1、什么是跨域?
跨域是浏览器为了安全而做出的限制策略。浏览器请求必须遵循同源策略:同端口、同域名、同协议。有时候我们发送请求会碰到接口不允许请求,可能就是遇到的跨域问题
2、如何解决跨域?
跨域的常见三种方法:(以vue为实列)
1、cors跨域
服务端设置,前端直接调用,后台允许前端某个站点进行访问
在封装的ajax中加入以下代码
Vue.http.options.credentials =true
2、jsonp跨域
首先安装jsonp
使用jsonp去请求
列如:
this.$http.jsonp('http://www.demo2.com:8080/login', {
params: {},
jsonp: 'onBack'}).then((res) => {
console.log(res);
})
3、接口代理跨域,实现本地开发环境下的转化
内部会通过node去转发别人的服务
使用接口代理也就是代理他的地址,后面的请求地址就类似于我们查找文件的路径
当我们访问下面这个地址时候
https://www.jianshu.com/writer/notebooks/
在vue.connfig.js中
module.exports = {
devServer:{
host:'localhost',
port:8080,
proxy:{
'/writer':{
target:'https://www.jianshu.com',
changeOrigin:true,
pathRewrite:{//转发地址,因为我们接口有很多比如/a、/b、/c这时候我们不可能写很多请求,可以写一个虚拟的接口,当访问到/writer会转发到/api中
'/api':' '
}
}
}
}
}
请求:
leturl ="writer/notebooks/";
jsonp(url,(err,res)=>{
letresult = res;
this.data = result;
})
}