vue前端公共访问http接口搭建

  1. 创建server.js请求路径
const ENV = "dev"
let origin = "";
switch(ENV){
     
    case "dev": //本地环境
        origin = ""
        break
    case "test": //测试环境
        origin = ""
        break
    case "prd": //生产环境
        origin = ""
        break
}
export default {
      origin }
  1. 创建http.js请求方法
import axios from "axios"
import server from "@/utils/server"

function get(url, params = {
     }){
     
    return request('get', url, params)
}
function post(url, params = {
     }){
     
    return request('post', url, params)
}
function request(methods, url, params){
     
    //初始化定义变量
    let config = {
     
        method: methods,
        url: server.origin + url,
        withCredentials: true,
    }
    //参数
    switch(methods){
     
        case 'get':
            config.params = params
            break
        case 'post':
            config.data = params
            break
    }
    //头部
    config.headers = {
      }
    //数据返回
    return new Promise((resolve, reject) => {
     
        axios(config).then( res => {
     
            if (!res || !res.data) {
     
                reject({
      code: 500, msg: "服务器异常"})
                return
            }
            const data = res.data
            const code = Number(data.code) 
            switch(code){
     
                case 10001:
                    resolve(data.data)
                    break
                case -99999:    //未登录
                    break
                default:
                    reject({
      code, msg: data.msg })
                    break
            }
        })
    })
}

export default {
     
    get,
    post
}
  1. 请求接口
import http from "@/utils/http"

const AAA = "/aaa"   //aaa接口
const BBB = "/bbb"  //bbb接口

export function aaaGet(params){
     
    return http.get(AAA , params).then(res => {
     
        //返回数据到页面
        return res
    })
}

export function bbbPost(params){
     
    return http.post(BBB , params).then( res => {
     
        //返回数据到页面
        return res
    })
}

你可能感兴趣的:(vue,vue)