26. Vue 使用 vue-resource 配置全局API域名

需求

在前面几篇中写了使用Vue-resource执行getpost请求的方法,如下:

methods: {
delList(id) { // 根据Id删除数据

console.log(`删除数据的id = ${id}`);

// 发送post请求,删除数据
// 设置 post 方法的第二个参数,设置传递的数据对象
// 通过 post 方法的第三个参数, { emulateJSON: true } 设置 提交的内容类型 为 普通表单数据格式 application/x-www-form-urlencoded
this.$http.post('http://127.0.0.1:5000/del_list', {id:id}, { emulateJSON: true }).then(result => {
console.log(result.body);

if (result.body.status === 0){
// 当执行成功,则立即刷新列表数据
this.getList();
}

})

},
getList(){
// 当发起get请求之后, 通过 .then 来设置成功的回调函数
this.$http.get('http://127.0.0.1:5000/get_list').then(function (result) {
// 注意:通过 $http 获取到的数据,都在 result.body 中放着
console.log(result.body.status); // 打印返回json中的status状态
console.log(result.body.messages); // 打印返回json中的messages数组

if (result.body.status === 0){
// 请求正常
this.list = result.body.messages; // 将messages数组赋值给this.list,然后this.list会渲染到列表中
console.log(this.list);
} else{
// 请求异常
alert("请求失败!")
}

})
}
...
},

可以从上面的两个请求来看,每个请求都写上了完整的api地址,如:http://127.0.0.1:5000/get_listhttp://127.0.0.1:5000/del_list

那么这里就存在一个问题,如果这样的接口很多,如果api服务的地址需要变动,那么就需要逐个去修改,这样就很费工作量了。

最好可以将服务器的URL部分作为一个全局配置的参数,统一配置控制,如:http://127.0.0.1:5000/

下面可以看看vue-resource的配置文档。

Vue-resource的配置文档说明

Github地址

https://github.com/pagekit/vue-resource

26. Vue 使用 vue-resource 配置全局API域名

配置说明文档

https://github.com/pagekit/vue-resource/blob/develop/docs/config.md

Configuration

Set default values using the global configuration.

使用全局配置设置http初始化值。

Vue.http.options.root = '/root'; // 配置服务域名的URL地址
Vue.http.headers.common['Authorization'] = 'Basic YXBpOnBhc3N3b3Jk'; // 通用的headers配置

Set default values inside your Vue component options.

使用Vue组件参数设置http的初始化值。

new Vue({

http: {
root: '/root', // 配置服务器域名的URL地址
headers: {
Authorization: 'Basic YXBpOnBhc3N3b3Jk' // 通用的headers配置
}
}

})

Note that for the root option to work, the path of the request must be relative. This will use this the root option: Vue.http.get('someUrl') while this will not: Vue.http.get('/someUrl').

注意,如果想要使用配置的「http根路径URL地址」 , 那么在写请求api地址的时候要写「相对路径」,例如:Vue.http.get('del_list') ,而不是写成绝对路径 Vue.http.get('/del_list'), 开头不能写上斜杠。

使用全局参数设置http的URL地址

26. Vue 使用 vue-resource 配置全局API域名

在浏览器查看network的请求api地址,如下:

26. Vue 使用 vue-resource 配置全局API域名

交流QQ群:

26. Vue 使用 vue-resource 配置全局API域名

26. Vue 使用 vue-resource 配置全局API域名


点击下面,查看更多Vue系列文章

26. Vue 使用 vue-resource 配置全局API域名26. Vue 使用 vue-resource 配置全局API域名


26. Vue 使用 vue-resource 配置全局API域名








原文始发于微信公众号(海洋的渔夫):26. Vue 使用 vue-resource 配置全局API域名

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/32228.html

(1)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!