# 在 Vue 上建置 Mock ###### tags: `Vue-cli`、`Mock`、`Vue2` ### 1. 這邊要模擬假 Url 呼叫,故須要透過 nodejs 來當作假後台,所以前台需要用 node 的 express 方式打接口,下載 body-parser 跟 express ```shell= npm install express --save npm install body-parser --save ``` ### 2. 創建 mock 資料夾與 mock.js #### mock.js ```javascript= const express = require("express") const bodyParser = require("body-parser") const server = express() const routes = require("./index.js") server.set("port", process.env.PORT || 3000) server.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*") res.header("Access-Control-Allow-Headers", "*") res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS") next() }) server.use( //用來解析request body bodyParser.urlencoded({ extended: true, parameterLimit: 10000, limit: 1024 * 1024 * 10 }) ) server.use(bodyParser.json()) server.use("/", routes) // http服務 server.listen(3000, () => { console.log(`Mock server is running at http://localhost:${server.get("port")}`) }) ``` ### 3.建立 API 呼叫方法 index.js ```javascript= const router = require("express").Router() /** * 呼叫 API 方法 * @param {String} method 請求方式 * @param {String} path API 路徑 * @param {Object} json 回傳的 json 物件 * @param {Number} time 模擬回傳的時間 */ const callApi = ({ method = "get", path, json, time = 800 }) => { const func = (req, res) => { setTimeout(() => { res.json(json.bind(this, req)()) }, time) } router[method](path, func) } callApi({ path: "{{實際 APIUrl}}", json: require("假資料路徑"), method: "post" }) module.exports = router ``` #### 假資料範例,某資料夾下檔案 ```javascript= const api = () => ({ errorCode: "", message: "", data: { result: true } }) module.exports = api ``` #### 注意!!! #### Mock Server 為自己設定的port,所以若要呼叫,則須針對 api 的 url 更改為該port號 #### 可透過下 npm scripts的方式來動態調整 ##### package.json ```javascript= "scripts": { "serve": "vue-cli-service serve --mode local", "serve:mock": "cross-env MOCK_MODE=true vue-cli-service serve --mode local", "build": "vue-cli-service build --no-clean", "lint": "vue-cli-service lint", "mock": "node mock/mock.js" } ``` ##### vue.config.js ```javascript= const isMock = process.env.MOCK_MODE === "true" module.exports = { ..., plugins: [ // new BundleAnalyzerPlugin(), new webpack.ProvidePlugin({ $: "jquery", jquery: "jquery", jQuery: "jquery", "window.jQuery": "jquery" }), new webpack.DefinePlugin({ VUE_APP_IS_MOCK: JSON.stringify(JSON.parse(isMock)) }), new compressionWebpackPlugin({ algorithm: "gzip", test: new RegExp("\\.(" + productionGzipExtensions.join("|") + ")$"), threshold: 10 * 1024, minRatio: 0.8, deleteOriginalAssets: false }) ] } ``` ##### api/index.js ```javascript= /* global VUE_APP_IS_MOCK */ const request = ({ name = "", url = "", options = {}, otherOption = {}, method = "post" }) => { let mockUrl = "" if (VUE_APP_IS_MOCK) { mockUrl = ~needMockApi.indexOf(name) ? `//${window.location.hostname}:3000` : "" } } ```