封装过程中遇到的问题简单记录下:1、post请求参数拼接到请求链接后面,检查了一下发现post请求到参数有问题修改如下
新建server.js文件
import axios from "axios"
import { Toast } from 'vant'
import qs from 'qs'
let serve = axios.create({
timeout: 10000,
// baseUrl: process.env.API,
})
serve.interceptors.request.use((config)=>{
console.log('config',config)
config.data = JSON.stringify(config.data); //数据转化,也可以使用qs转换
config.headers = {
'Content-Type':'application/json' //配置请求头
}
// let token = ''
// if(token) {
// config.headers.token = token
// }
//config.data = qs.stringify(config.data)
return config
},err=>{
console.log('err',err)
// return Promise.reject(err)
})
serve.interceptors.response.use((response)=>{
let code = response.data.code
if(response.status==200) {
return response
}else {
Toast(response.data.message)
}
},err=>{
if(err && err.response) {
let res = err.response.status
switch(res) {
case 400:
err.message = '错误请求';
break;
case 401:
err.message = '未授权,请重新登录';
break;
case 403:
err.message = '拒绝访问';
break;
case 404:
err.message = '请求资源不存在';
break;
case 405:
err.message = '请求路径出错';
break;
case 500:
err.message = '服务端出错';
break;
case 502:
err.message = '网络出错';
break;
case 503:
err.message = '服务不可用';
break;
case 504:
err.message = '网络超时';
break;
}
}else {
err.message = '连接服务器失败'
}
Toast(err.message)
return Promise.reject(err.response)
})
export default serve
httpRequest.js文件
import Vue from 'vue'
import VueRouter from 'vue-router'
import serve from './serve.js'
const httpRequest = {
get(url,params) {
const config = {
method: 'get',
url:url
}
if(params) {
config.params = params
}
return serve(config)
},
post(url,params) {
const config = {
method: 'post',
url:url
}
if(params) {
config.data = params
}
return serve(config)
},
put(url,params) {
const config = {
method: 'put',
url:url
}
if(params) {
config.params = params
}
return serve(config)
}
}
export default httpRequest