vue axios http请求封装
程序员文章站
2022-07-02 12:23:32
...
- 新建http.js
import axios from "axios";
import iView from "iview";
export const URL = "http://11.11.11.11:8080/";
const service = axios.create({
baseURL: URL,
timeout: 5000 * 60 * 1, //分钟
headers: {
"Content-Type": "application/json;charset=UTF-8"
}
});
// 请求拦截
service.interceptors.request.use(
config => {
if (!config.headers["Authorization"]) {
//带token
if (localStorage.token) {
config.headers["Authorization"] = localStorage.token;
}
}
return config;
},
error => {
iView.Message.error("请求超时!");
return Promise.reject(error);
}
);
// 响应拦截
service.interceptors.response.use(
response => {
let token = response.data["token"];
if (token && token != "") {
localStorage.token = token;
}
if (response.status && response.status != 200) {
iView.Message.error(response.statusText || "业务异常!");
}
if (response.data.status == 101) {
iView.Message.warning("权限不足!!!");
}
return response.data;
},
err => {
console.log(err);
iView.Message.error("请求失败!");
return Promise.reject(err);
}
);
export default service;
- 封装对应的请求,新建 login.js
import http from "@/plugins/http";
/***用户登录****/
export function Login(params) {
return http({
url: "/login",
method: "post",
data: { ...params }
});
}
- 使用
import { Login } from "@/api/login";
userLogin({
username: 123,
password: 456
}).then(res => {
// 请求处理的回调
}).catch(() => {
// 请求失败的回调
});
上一篇: STM32 NVIC 中断优先级
推荐阅读