安装依赖
npm i express mockjs nodemon body-parser --save-dev
- Express:Node.js Web 应用程序框架
- Mock.js:模拟数据生成
- nodemon:监听变化,实现热更新
- body-parser:请求体解析
编写 server.js
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
// 解析 application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// 解析 application/json
app.use(bodyParser.json())
app.all('*', function (req, res, next) {
// 允许跨域
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS')
next()
})
app.post('/test', (req, res) => {
res.json({ hello: 'world' })
})
app.listen('3000', () => console.log('Server on 3000'))
编写 nodemon.js
const nodemon = require('nodemon')
const path = require('path')
const resolve = (file) => path.resolve(__dirname, file)
/**
* script 重启的脚本
* ext 检测的文件类型
* watch 监听哪些文件
* ignore 忽略哪些文件
*/
const server = resolve('server.js')
nodemon({
script: server,
ignore: [],
watch: [
resolve('modules/'),
server
],
ext: 'js json'
})
nodemon.on('start', function () {
console.log('mockServer has started')
}).on('quit', function () {
console.log('mockServer has quit')
process.exit()
}).on('restart', function (files) {
console.log('mockServer restarted due to: ', files)
})
添加启动命令
"scripts": {
"mock-server": "node nodemon.js"
}
启动后访问http://localhost:3000/test
测试。
标签:Express,const,app,express,nodemon,js,Mockjs,server From: https://www.cnblogs.com/Higurashi-kagome/p/17737490.html参考:express+mockjs 搭建一个 mock 服务方便前端开发、express+mockjs+nodemon 搭建一个 mock 服务