节点 JSON-服务器返回 MOCK post 响应

Node JSON-Server returning MOCK post response

我正在尝试使用 https://www.npmjs.com/package/json-server 作为模拟后端,我能够为 get 匹配 URL,但是我如何 return 为 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 等。具体取决于一些数据。

最大的问题是我的代码没有 returning 对 POST 的任何响应,它只在 JSON

中插入记录

默认情况下 POST 通过 json 服务器的请求应该给出 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();
  }  
});

完整代码(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