首页 > 移动平台 > 详细

vue 中axios

时间:2020-12-28 16:21:02      阅读:36      评论:0      收藏:0      [点我收藏+]
import axios from "axios";
import { Message } from "element-ui";
import router from "../router/index";
const NODE_ENV = process.env.NODE_ENV;

let http = axios.create({
    baseURL: NODE_ENV === "development" ? "/api(开发环境)" : "正式环境后台地址", // 开发环境/正式环境(打包后)
    withCredentials: true,
    headers: {
        "Content-Type": "application/json",
        "Token": ‘‘
    },
});

function apiAxios(method, url, params, response) {
    http({
        method: method,
        url: url,
        data: method === "POST" || method === "PUT" ? params : null,
        params: method === "GET" || method === "DELETE" ? params : null,
    }).then(function (res) {
        response(res);
    }).catch(function (err) {
        response(err);
    })
}
// 添加请求拦截器
http.interceptors.request.use(function (config) {
    const token = localStorage.getItem("token") || "";
    config.headers[‘Token‘] = token;
    return config;
}, function (error) {
    return Promise.reject(error);
});

// 添加响应拦截器
http.interceptors.response.use(function (response) {
    return response;
}, function (error) {
    if(error.response.data.message == "token信息失效") {
        Message({
            showClose: true,
            message: "身份信息失效,请重新登录!",
            type: "warning"
        });
        setTimeout(function(){
// 清除token 跳转登录页 localStorage.removeItem(
"token"); router.push({ path: "/" }) },2000); } return Promise.reject(error); });
export
default { get: function (url, params, response) { return apiAxios("GET", url, params, response) }, post: function (url, params, response) { return apiAxios("POST", url, params, response) }, put: function (url, params, response) { return apiAxios("PUT", url, params, response) }, delete: function (url, params, response) { return apiAxios("DELETE", url, params, response) } }


// 请求示例
LoginBtn() {
this.LoginIstrue = true; if(this.name == ‘‘){ this.$message({ showClose: true, message: ‘用户名不可为空!‘, type: ‘warning‘ });return false }else if(this.pwd == ‘‘) { this.$message({ showClose: true, message: ‘密码不可为空!‘, type: ‘warning‘ });return false } let url = ‘*****‘; let pwd = this.$md5(this.pwd); let params = { account: this.name, password: pwd, }; this.$axios.get(url, params, res => { if(res.data.code == 0) { localStorage.token = res.data.data; this.$router.push({ path: ‘/home‘ }) this.$message({ showClose: true, message: ‘欢迎您,管理员!‘, type: ‘success‘ }); this.LoginIstrue = false; }else{ this.$message({ showClose: true, message: res.data.message, type: ‘warning‘ }); this.LoginIstrue = false; } }); }

 

 

 

vue 中axios

原文:https://www.cnblogs.com/zm-97/p/14201539.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!