gpt4 book ai didi

javascript - 返回 MOCK 后响应的 Node JSON-Server

转载 作者:行者123 更新时间:2023-12-04 13:17:53 24 4
gpt4 key购买 nike

我正在尝试使用 https://www.npmjs.com/package/json-server作为一个模拟后端,我可以匹配获取的 URL,但是我如何才能为 POST 调用返回一些模拟响应。

Like for create user URL will be like


 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"}

在某些情况下,我还想根据某些数据发送自定义 http 代码,例如 500,423,404,401 等。

最大的问题是我的代码没有为 POST 返回任何响应,它只在 JSON 中插入记录

最佳答案

默认情况下,通过 json-server 的 POST 请求应该给出 201 created 响应。

如果您需要自定义响应处理,您可能需要一个中间件来获取 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();
}
});

完整代码(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");
});

您可以使用 node index.js 启动 json-server

关于javascript - 返回 MOCK 后响应的 Node JSON-Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58297415/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com