没有特别的幸运,那么就加倍的努力!!!
什么是跨域?
简单的来讲——就是违背了同源策略,
“协议+域名+端口” 三者只要有一者不同,就会存在跨域
在我们前端开发中,常常碰到一些接口上的跨域问题,现在分享几种常用的解决方案:
方案一:jsonp
1.jquery ajax:
$.ajax({
url: 'http://www.tpWang.com:8080/login',
type: 'get',
dataType: 'jsonp', // 请求方式为jsonp
jsonpCallback: "handleCallback", // 自定义回调函数名
data: {}
});
2.vue.js:
this.$http.jsonp('http://www.tpWang.com:8080/login', {
params: {},
jsonp: 'handleCallback'
}).then((res) => {
console.log(res);
})
方案二:页面代理(vue)
在config文件下index.js文件
找到proxyTable 一般在十几行的样子
proxyTable: {
'/api': {
target: 'http://api.zhuishushenqi.com', // 设置你调用的接口域名
changeOrigin: true, // 是否跨域
pathRewrite: {
'^/api': '/' // 这里可以理解为用‘/api’来代替target里面的地址,例如我们调用http://jspang.com/DemoApi/oftenGoods.php,直接写成‘/api/DemoApi/oftenGoods.php’就可以了
},
}
},
XXX.vue页面
methods:{
getSlide:function(){
var _this = this;
axios.get("/api/ranking/gender").then(function(res){
console.log(res)
})
},
}
方案三:nginx反向代理(js,jq 推荐方案三)
常见误区
- 无用的ACA-Header ?
网上很多的nginx跨域设置里面都加了跨域header设置相关的内容,比如
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' "true";
add_header 'Access-Control-Allow-Headers' 'X-Requested-With';
想想上面的原理,各位看官觉得这个还有用么?ACA(Access-Control-Allow-)系列的header本身是为了cors中做协商跨域而配置的,在这里配这个纯属多此一举。
2. proxy_pass 域名带不带‘斜杠/’ ?
同样的,在网上看到了有的网友在配置proxy_pass的时候,会在后面加一个斜杠,如下,然后说报错啦,找不到接口啦~咋整啊~
location /api {
#proxy_pass https://b.test.com;
proxy_pass https://b.test.com/;
}
看到这个我们来想一想哈,proxy_pass的作用是抓发,加了斜杠意味着所有的/api请求都会转发到根目录下,也就是说 /api 会被 / 替代,这个时候接口路径就变了,少了一层/api。而不加斜杠的时候呢?这代表着转发到b.test.com 的域名下,/api的路径不会丢失。
针对这种情况,如果后端接口统一有了规定前缀,比如/api,那你这里就不要配置斜杠了。另一种情况,后端接口shit一样,没有统一前缀,这边又要区分,那就在前端所有接口都加一个统一前缀,比如/api,然后通过加斜杠来替换掉好了~
1.在本地起个服务,先下载nginx包
https://github.com/15171222839/nginx
2.对应的配置项改下,其他无需改动
改动页面nginx.conf文件
//路径 nginx\nginx\conf
方法一: //要把 自己代码文件放到nginx文件包中html文件上
server {
listen 8088; //反代理 本地代理端口号
server_name localhost; //本地
location / {
proxy_pass http://192.168.88.203:8089/; //代理接口(后端传入)
index index.html index.htm; // 默认跳转页面(可写可不写)
}
}
方法二:
server {
listen 8080;
server_name localhost;
location / {
root C:/Users/Administrator/Desktop/wenling2020; //对应自己代码文件路径
}
location /cjApi { //中转匹配,cjApi随意命名
rewrite ^/cjApi/(.*)$ /$1 break;
proxy_pass http://192.168.88.41:80/;
}
}
//页面接口调用
方法一:
var api = 'http://localhost:8088'
//地区
function loc(){
$.ajax({
type:"get",
url: api+"/capita/largeScreenData/getRegionInfo",
success:function(res){
console.log(res)
}
})
}
loc()
方法二:
var url = 'http://127.0.0.1:8080/';
var envir='cjApi';
var token;
$.ajax({
type: 'post',
async: true,
data:{username:'admin',password:'123456',rememberMe:true},
url:url+ envir+'/login',
success: function (data) {
console.log(data);
},
});
页面访问 http://127.0.0.1:8088/views/ 对应文件路径(wenling2020/views/index.html)