首页 技术 正文
技术 2022年11月21日
0 收藏 882 点赞 3,445 浏览 1386 个字

闲着没事,假期敲vue 请求数据,总结下vue跨越问题

第一种.服务器服务器不支持跨域请求

  1.当跨域无法请求的时候我们可以修改工程下config文件夹下的index.js中的dev:{}部分。

添加下面的代码:

   proxyTable: {
'/api': {
target: 'http://api.douban.com/v2',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},

将target设置为我们需要访问的域名。

2.然后在main.js中设置全局属性:

Vue.prototype.HOST = '/api'

3.我们就可以在全局使用这个域名了,如下:

var url = this.HOST + '/movie/in_theaters'
this.$http.get(url).then(res => {
this.movieList = res.data.subjects;
},res => {
console.info('调用失败');
});

第二种:服务器端支持跨域

    String data = JsonUtil.toJsonNonNull(pubXtzdBos);    OutputStream out = response.getOutputStream();     out.write(data.getBytes("UTF-8"));//以UTF-8进行编码      response.setHeader("Access-Control-Allow-Origin", "*");
//告诉浏览器编码方式
response.setHeader("Content-Type","text/html;charset=UTF-8" );

就是能支持跨域那就可以使用jsonp来请求了。jsonp实际上就是通过添加script标签来添加的,

请求回来的数据也是js格式。axios目前还不支持,只能自己手动创建script标签,把请求的地址赋给script标签的src属性,最后添加到head标签上,等到请求返回再把标签删掉:

   jsonpRequest: function (a, e) {
this._ajaxTimer && clearTimeout(this._ajaxTimer);
this._ajaxTimer = setTimeout(function () { var request_script = document.createElement('script');
request_script.setAttribute("id", "request_script");
request_script.src = 'http://xxxx'+'&t=' + Date.now();
window.callback = function (response) {
// 移除脚本
document.body.removeChild(document.getElementById('request_script'));
console.log(response.content);
}
document.body.appendChild(request_script);
}, 500);
},

讲真,本地开发适合第一种吧 然后可以正常使用axios进行ajax请求了,

但这样只能在开发模式下才能使用。打包部署的时候建议使用nginx做代理

,我也没有试过第二种,也是查阅资料总结的,哈哈

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,488
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,736
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,487
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,127
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,289