Vue中使用Axios请求后端接口的方法总结
1.在入口文件引入axios并配置请求头根路径和请求头拦截
// 引入axios
import axios from axios
// 设置请求根路径
axios.defaults.baseURL=http://127.0.0.1:8888/api/private/v1/
// 设置请求头拦截
axios.interceptors.request.use(config => {
config.headers.Authorization = window.sessionStorage.getItem(token);
console.log(config);
// 在最后必须 return config
return config
})
// 把axios挂到Vue实例对象上
Vue.prototype.$http = axios
经过以上设置则可以通过 this.$http发送axios请求后端接口
2.发送各类请求携带参数的格式:
(1)get请求
const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`,
{ params: { sel: this.activeName } }
);
// 若要求参数携带在url中 可以通过 `` 包裹后端地址,使用${}在url中携带对应参数
// 不携带在url的参数需要通过 params传递参数
// 若参数不携带在url中,且参数很多,可以把接口所需参数打包成一个对象,通过params把由各个参数组成的对象直接传给后端接口
(2)post请求
const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`,
{
attr_name: this.addForm.attr_name,
attr_sel: this.activeName,
}
);
// 若要求参数携带在url中 可以通过 `` 包裹后端地址,使用${}在url中携带对应参数
// post请求不携带在url中的参数 需要通过 {} 以参数名:参数值 的格式逐一进行传递,每个参数以逗号分隔
(3)delete请求
请求路径:users/:id 不能为空`参数是url参数:id`
async removeUserById(id) {
const { data: res } = await this.$http.delete("users/" + id);
},
// 不携带在url中的url参数 使用字符串拼接的形式传递参数
// 若要求参数携带在url中 可以通过 `` 包裹后端地址,使用${}在url中携带对应参数
(4)put请求
const { data: res } =
await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
{
attr_name: this.editForm.attr_name,
attr_sel: this.editForm.attr_sel,
}
);
// 若要求参数携带在url中 可以通过 `` 包裹后端地址,使用${}在url中携带对应参数
// post请求不携带在url中的参数 需要通过 {} 以参数名:参数值 的格式逐一进行传递,每个参数以逗号分隔
