
No more than code.
项目目录下创建 mock 文件夹,添加 db.json 文件
build/dev-server.js 中添加如下代码
npm run dev 启动后,可以通过 http://localhost:项目端口号/mock/db.json 访问数据,proxyTable对应设置代理即可(代理设置方法与解决跨域方法相似)
package.json scripts中添加命令
"mock": "json-server --watch mock/faker-data.js",
"mockdev": "npm run mock | npm run dev"
执行$ npm run mock 命令,运行 mock server
访问 http://localhost:3000/
mock 目录下创建 faker-data.js
var faker = require("faker");
module.exports = function a() {
faker.locale = "zh_CN";
var _ = require("lodash");
return {
people: _.times(10, function (n) {
return {
id: n,
name: faker.name.findName(),
email: faker.internet.email(),
image: faker.image.avatar(),
profile:[{
website: faker.internet.url(),
address: faker.address.streetAddress() + faker.address.city() + faker.address.country(),
bio: faker.lorem.sentences()
}]
}
}),
address: _.times(100, function (n) {
return {
id: faker.random.uuid(),
city: faker.address.city(),
county: faker.address.county()
}
})
}
}
json server 使用 RESTful 架构,GET请求可以获取数据,POST 请求则是添加数据。 在开发过程中,有时候想直接模拟获取POST请求返回结果,可以添加 express 中间件 将POST请求转为GET请求。
mock 目录下创建 post-to-get.js
module.exports = function (req, res, next) {
req.method = "GET";
next();
}
启动命令添加运行中间件 –m mock/post-to-get.js
"mock": "json-server --watch mock/db.json --m mock/post-to-get.js"
重新启动服务,POST请求就被转换为GET请求了,其他需求也可以通过添加不同的中间件实现。
在 config/index.js 的 proxyTable 将请求映射到 http://localhost:3000
proxyTable: {
'/api': {
target: 'http://localhost:3000/',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
代码中添加请求以测试效果
this.$http.get("http://localhost:3000/people")
.then((res) => {
console.log(res)
})
$ npm run mockdev 启动带mock 数据的本地服务,结果如下