新建文件夾mockServe, 新建server.js,
2.將mock的數據(data.json)放入mockServer文件中,
3. npm init -y, 安裝express包 npm i express
4.在server.js中搭建服務, npm start 啟動服務
//引入express const express = require('express') // 創建服務器應用實例 const app = express() // 引入json數據 const appData = require('./data.json') const seller = appData.seller const goods = appData.goods const ratings = appData.ratings // 注冊路由 app.get('/seller', function(req, res){ // res.json(數據)->把數據轉換成json字符串,根據數據內容,修改了Content-Type內部的編碼格式,並返回 res.json({ error:0, data:seller }) }) app.get('/goods', function(req, res){ res.json({ error:0, data:goods }) }) app.get('/ratings', function(req, res){ res.json({ error:0, data:ratings }) }) // 3.運行服務器應用,並監聽端口 // 端口號可以任意選擇,但是不要小於1000 app.listen("5000",function(err){ if(err){ console.log('服務器連接失敗',err) }else{ console.log('服務器啟動成功,啟動於http://localhost:5000上') } })
此時在vue項目中的main.js測試下有沒有數據出現,
import axios from "axios"; axios.get('/seller').then(v=> console.log(v))
此時並沒有數據返回,因為運行vue項目默認在本機搭建了8080端口的服務,去請求5000端口的服務,已經跨域了,我們需要在vue.config.js中設置代理
module.exports = { lintOnSave: false, devServer: { // 端口配置 // port: 1888, // 友情提示:改完請重啟項目才能生效!!! // 反向代理配置 //需要轉發路由的路徑 proxy: { "/api": { target: "http://localhost:5000", pathRewrite: { "^/api": "" }, changeOrigin: true } } } };
然后在去main.js去請求數據即可
import axios from "axios"; axios.get('/api/seller').then(v=> console.log(v))
第二種更簡便的方法,在webpack的配置文件vue.config.js的devServer配置mock服務,因為vue項目運行的服務,以及mock的服務都在devServer中,同一個服務,不存在跨域
devServer.before
function (app, server, compiler)
提供在服務器內部先於所有其他中間件執行自定義中間件的功能。這可以用於定義自定義處理程序,例如:
webpack.config.js
module.exports = { //... devServer: { before: function(app, server, compiler) { app.get('/some/path', function(req, res) { res.json({ custom: 'response' }); }); } } };
const appData = require("./data.json"); const seller = appData.seller; const goods = appData.goods; const ratings = appData.ratings; module.exports = { lintOnSave: false, devServer: { // 端口配置 // port: 1888, // 友情提示:改完請重啟項目才能生效!!! // 反向代理配置 //需要轉發路由的路徑 // proxy: { // "/api": { // target: "http://localhost:5000", // pathRewrite: { "^/api": "" }, // changeOrigin: true // } // } before(app) { app.get("/api/seller", function(req, res) { res.json({ errno: 0, data: seller }); }); app.get("/api/goods", function(req, res) { res.json({ errno: 0, data: goods }); }); app.get("/api/ratings", function(req, res) { res.json({ errno: 0, data: ratings }); }); } } };
此時在vue項目中的main.js測試下有沒有數據出現
import axios from "axios";
axios.get('/seller').then(v=> console.log(v))