Anu*_*ngh 4 javascript mocking node.js json-server
我正在尝试使用https://www.npmjs.com/package/json-server作为模拟后端,我能够匹配 get 的 URL,但如何为 POST 调用返回一些模拟响应。
就像创建用户 URL 一样
URL - http://localhost:4000/user
Method - POST
Request Data - {name:"abc", "address":"sample address"}
expected response -
httpStats Code - 200,
Response Data - {"message":"user-created", "user-id":"sample-user-id"}
Run Code Online (Sandbox Code Playgroud)
在某些情况下,我还想发送自定义 http 代码,例如 500,423,404,401 等,具体取决于某些数据。
最大的问题是我的代码没有返回任何 POST 响应,它只在 JSON 中插入记录
默认情况下,通过 json-server 的 POST 请求应给出 201 创建的响应。
如果您需要自定义响应处理,您可能需要一个中间件来获取 req 和 res 对象。
在这里,我添加了一个中间件来拦截 POST 请求并发送自定义响应。您可以根据您的具体情况进行调整。
// Custom middleware to access POST methods.
// Can be customized for other HTTP method as well.
server.use((req, res, next) => {
console.log("POST request listener");
const body = req.body;
console.log(body);
if (req.method === "POST") {
// If the method is a POST echo back the name from request body
res.json({ message:"User created successfully", name: req.body.name});
}else{
//Not a post request. Let db.json handle it
next();
}
});
Run Code Online (Sandbox Code Playgroud)
完整代码(index.js)..
const jsonServer = require("json-server");
const server = jsonServer.create();
const router = jsonServer.router("db.json");
const middlewares = jsonServer.defaults();
server.use(jsonServer.bodyParser);
server.use(middlewares);
// Custom middleware to access POST methids.
// Can be customized for other HTTP method as well.
server.use((req, res, next) => {
console.log("POST request listener");
const body = req.body;
console.log(body);
if (req.method === "POST") {
// If the method is a POST echo back the name from request body
res.json({ message:"User created successfully", name: req.body.name});
}else{
//Not a post request. Let db.json handle it
next();
}
});
server.use(router);
server.listen(3000, () => {
console.log("JSON Server is running");
});
Run Code Online (Sandbox Code Playgroud)
你可以使用以下命令启动 json-servernode index.js