前端跨域问题
程序员文章站
2024-02-21 22:16:04
...
没有特别的幸运,那么就加倍的努力!!!
什么是跨域?
简单的来讲——就是违背了同源策略,
“协议+域名+端口” 三者只要有一者不同,就会存在跨域
在我们前端开发中,常常碰到一些接口上的跨域问题,现在分享几种常用的解决方案:
方案一: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 推荐方案三)
1.在本地起个服务,先下载nginx包
https://github.com/15171222839/nginx
2.对应的配置项改下,其他无需改动
改动页面nginx.conf文件
//路径 nginx\nginx\conf
server {
listen 8088; //反代理 本地代理端口号
server_name localhost; //本地
location / {
proxy_pass http://192.168.12.203:8089/; //代理接口(后端传入)
index index.html index.htm; // 默认跳转页面(可写可不写)
}
}
//页面接口调用
var api = 'http://localhost:8088'
//地区
function loc(){
$.ajax({
type:"get",
url: api+"/capita/largeScreenData/getRegionInfo",
success:function(res){
console.log(res)
}
})
}
loc()
拿着 不谢 请叫我“锤” 谢谢!!!
上一篇: 前端跨域问题
下一篇: 计算机网络http的具体应用