今天我们来讲讲vue中调api的两种常见方法。
由于vue2.0开始,对vue-resource不在维护更新。所以导致很多人开始入坑axios。
当我用起了axios,嗯,它是真的坑。最坑的是它不支持跨域。
如果你项目打包上线依旧需要跨域,我劝你就不要用axios了,会把自己坑死的。(这时候就可以用vue-resource)
但是如果只是在环境上测试,你可以使用proxyTable
代理。
具体使用如下,找到config文件夹中的index.js文件:
1
2
3
4
5
6
7
8
9proxyTable: {
'/api':{
target:'https://api.douban.com',
changeOrigin:true,
pathRewrite:{
'/api':''
}
}
}
怎么调用?
如下:1
2
3
4that.$axios.post('/api/v2/movie/top250').then(function(response){console.log(response.data);
}).catch(function(error){
console.log(error);
});
这里就相当于用/api==https://api.douban.com
但是如果打包后还是要实现跨域,那么用vue-resource
吧,小伙子别执着了。
vue - reource 安装步骤
1.npm install vue-resource --save
2.找到main.js
,加入下面代码。
import VueResource from ‘vue-resource’
Vue.use(VueResource)
跨域调用:
that.$http.jsonp(“http://xxxxxxxxxxx",{params:{"callback":"jsonPCallback"}}).then(function(response){
console.log(response.body);
});
ok,大功告成。