English | 简体中文
a mock middle ware base on express.js mock the real ajax request, support the json, js; and more easy to configure the proxy of your project
npm install super-mock-middleware --save-dev
create-react-app react-demo
new file: "react-demo/src/setupProxy.js"
const SuperMock = require('super-mock-middleware);
module.exports = function (app) {
SuperMock.install(app);
}
const express = require('express');
const SuperMock = require('super-mock-middleware);
const app = express();
SuperMock.install(app);
// other middlewares
// ...
app.listen(3000);
webpack.config.js
const SuperMock = require('super-mock-middleware);
module.exports = {
//...
devServer: {
before: function (app) {
SuperMock.install(app);
},
},
};
mock data path is /mock in project root it will search the directory and try match the js file and json file; for example: /api/user/userList try to match file as following rule(Depth-First-Search):
- /mock/api/user/userList.(js|json)
- /mock/**/user/userList.(js|json)
- /mock/**/userList.(js|json)
- /mock/userList.(js|json)
the middleware delete the require cache of the path: /mock, so it works as you modify it。and you don't need to restart the project;
{
"success": true,
"code": "0000",
"data" : {
"name": "chentangsong",
"job": "front end",
"hobies": "coding, beer, meat"
}
}
// this is a module to respone the request
module.exports = {
success: true,
code: "0000",
data: [
{name: 'chentangsong', company: 'pingan'},
{name: 'robot', company: 'microsoft'}
]
}
module.exports = function(req, res, next){
let userId = req.query.userId || req.body.userId;
let userList = [
{userId:123, name: 'chentangson-vip', company: 'pingan'},
{userId:456, name: 'robot-vip', company: 'microsoft'}
];
let user = userList.find(u=>u.userId == userId);
if (!user) user = userList[0];
res.send({
data: user,
success: true,
code: "0000"
});
}
visit the page: /devTools/ turn off/on the mock, when the toggle on, all then requests go to the middleware, when it match a file, it will response and return. otherwire, it go ahead to next middleware.
visit the page: /devTools/#/proxy you can try it out before adding a proxy route or modifing a proxy rule; enable/disable a proxy rule, it works as you commit, do not need to restart you project.