mock模拟接口,使用默认的devserve 完成,考虑到这边有后台提供的模拟数据,随不需要自己随机生成数据,如果说有需要自己随机生成数据,可以使用mockjs
写mock接口
-
在src/ 目录下新建mock目录,存放所有的mock文件 -
在src/mock/ 目录下新建home.js -
home.js mock 文件内容
const getAdverising = (request, response) => {
const result = {
"errorCode": 0,
"errorMessage": "success",
"data": { },
"success": true
}
response.json(result)
}
const getProductList = (request, response) => {
console.log('request', request)
let list = []
let result = {
"errorCode": 0,
"errorMessage": "success",
"data": {
"product_list": list,
"page_info": {
"page_size": 10,
"index": 1,
"has_more": true,
"count": 10
}
},
"success": true
}
response.json(result)
}
const HomeMockApi = (app) => {
app.post('/mock/adverising/getAdvertisingList', getAdverising)
app.post('/mock/product/getProductLisgt', getProductList)
}
module.exports = HomeMockApi
-
在src/ 目录下新建vue.config.js 文件,配置devsever
const HomeMockApi = require('./src/mock/home')
module.exports = {
devServer: {
before(app, ) {
HomeMockApi(app)
}
}
axios 封装
-
安装axios
npm i axios -s
or
yarn add axios
-
在 src/utils/ 目录下新建 request.js -
在src/urils 新建config.js 文件,并将常用变量名抽离放在此处 export const REJIECTURL = 'REJIECTURL'
export const TOKENKEY = 'TOKENKEY'
export const USERINFO = 'USERINFO'
-
axios 封装 import axios from 'axios'
import { Toast } from 'vant'
import * as sysConfig from './config'
const timeout = 60000
const baseURL = 'http://localhost:8080'
let request = axios.create({
timeout,
baseURL
})
const addToken = config => {
let token = localStorage.getItem(sysConfig.TOKENKEY)
config.headers.Authorization = `Bearer ${token}`
return config
}
const addParams = config => {
let userId = 'userId'
let deviceId = 'h5'
let params = {
userId,
deviceId
}
let key = config.method == 'post' ? 'data' : 'params'
config[key] = {
...config[key],
...params
}
return config
}
request.interceptors.request.use(config => {
return Promise.resolve(config)
.then(addToken)
.then(addParams)
})
const checkNetWorkStatus = response => {
console.log('response', response)
let {
status,
message
} = response
const errorCodes = [404, 403, 500, 502, 405]
if (errorCodes.includes(status)) {
Toast({
type: 'fail',
message
})
}
return response
}
const clearLoginInfo = () => {
const keys = [
sysConfig.TOKENKEY,
'userId'
]
keys.map(key => localStorage.removeItem(key))
}
const checkCode = response => {
let { errorCode, errorMessage } = response.data
if (errorCode !== 0) {
Toast({
type: 'fail',
message: errorMessage
})
}
let codes = [401, 403]
if (codes.includes(errorCode)) {
clearLoginInfo()
sessionStorage.setItem(sysConfig.REJIECTURL, location.href)
}
return response
}
request.interceptors.response.use(response => {
return Promise.resolve(response)
.then(checkNetWorkStatus)
.then(checkCode)
.then(response => response.data)
})
export default request
|