做个记录用
使用场景:统一写在api.js文件中的接口,全局都可以调用,但是统一经过了请求拦截处理加了身份识别的token,和判断身份信息失效码值的请求响应拦截。有些接口不需要加token,所以只能在页面或js文件中直接使用接口的url来请求后台。 以下都按post 来举例
vue页面中:
(1) this.$http.post
(a) 需要安装并引入 vue-resource
npm install vue-resource --save
(b) 并在main.js中引入声明:
import VueResource from 'vue-resource';
Vue.use(VueResource);
(c) .vue文件中使用:
注意,经过实践发现 vue-resource版本不同,写法也有些不同,否则不会发出请求。
// vue-resource 版本不同 格式也不同否则无法发送信息
// 1.5.1 版本
test(){
// request 为请求参数
this.$http.post(
'/openapi/loan/data/queryData',
request,
headers:{authorization: "xxxx"}).then(res=>{})
}
// 1.5.2 版本
test(){
this.$refs.msgForm.validate(v => {
this.$http({
// url两种写法都可以
// url: '/gateway/oauth/server/api/xxx',
url:"https://xxx/gateway/oauth/server/xxx",
method: 'post',
param,
headers: {
authorization: "xxxx"
}
}).then((res)=>{
})
});
},
(2)axios.post
(a) 需要安装并引入 axios
npm install axios
(b) 在需要使用的.vue页面中引入
import axios from 'axios'
// url 可以写具体的也可以单写接口路径
axios.post('接口地址/user',{
headers:{authoratun:token},
params:{id:1234}
})
.then((res)=>{
})
.catch(error=>{…})
(3)Vue.http.post
Vue默认安装,应该不需要重新安装的,在要使用的.js文件中引入
import Vue from 'vue'
Vue.http.post('/gateway/xxx/server/xxx',params,
{
headers: {
authoratun: "xxxx"
}
}
)
.then(res => {}).catch(err => {});