axios&&mock&&json5&&api&&vue.config.js在開發(fā)環(huán)境中

// 環(huán)境的切換
1.htttp
if (process.env.NODE_ENV == 'development') {
  axios.defaults.baseURL = 'http://xxxx:8080';
} else if (process.env.NODE_ENV == 'debug') {
  axios.defaults.baseURL = 'http://xxxxxx:8080';
} else if (process.env.NODE_ENV == 'production') {
  axios.defaults.baseURL = 'http://xxxxxx:8090';
}

2.api
import axios from '../request/http'

export const getName = () => {
    return axios({
        url: '/user/userinfo',
        method: 'get'
    })
}
export const getGoods = () => {
    return axios({
        url: '/user/goods',
        method: 'get'
    })
}

3.mock的index.js
const fs = require('fs');
const path = require('path');
const Mock = require('mockjs');
const JSON5 = require('json5');

// 讀取json文件
function getJsonFile(filePath) {
  let json = fs.readFileSync(path.resolve(__dirname, filePath), 'utf-8');
  return JSON5.parse(json);
}

module.exports = function (app) {
  if (process.env.MOCK == 'true') {
    // 監(jiān)聽http請求
    app.get('/user/userinfo', function (rep, res) {
      // getJsonFile方法定義了讀取json文件
      let json = getJsonFile('./userInfo.json5');
      // 將json傳入Mock.mock方法中,生成的數(shù)據(jù)返回瀏覽器
      res.json(Mock.mock(json));
    })
    app.get('/user/goods', function (rep, res) {
      // getJsonFile方法定義了讀取json文件
      let json = getJsonFile('./goods.json5');
      // 將json傳入Mock.mock方法中,生成的數(shù)據(jù)返回瀏覽器
      res.json(Mock.mock(json));
    })
  }
}


4.json5
{
    id: "@id()", 
    username: "@cname()", // 隨機生成中文名
    date: "@date()", // 隨機生成日期
    avatar: "@image('200x200','red','#fff','avatar')", // 隨機生成圖片
    description: "@paragraph()", // 隨機生成描述
    ip: "@ip()", // 隨機IP
    email: "@email()", // 郵件
    "array|1-4": [
        {
            "id|+1": 1, 
            name: "@cname"
        }
    ]
}

5..env.development
MOCK = true

6.vue.config.js
devServer: {
    before: require('./src/mock/index.js'),
    open: true,
    host: 'xxxxxx',
    port: 8080,
    hotOnly: true,
    watchContentBase: true,
    proxy: {
      "/api": {
        target: "http://xxxxxxx:8080",
        pathRewrite: {
          "^/api": ""
        }
      }
    }
  }


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容