首页 > 解决方案 > 返回 MOCK 后响应的节点 JSON-Server

问题描述

我正在尝试使用https://www.npmjs.com/package/json-server作为模拟后端,我能够匹配获取的 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"}

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

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

标签: javascriptnode.jsmockingjson-server

解决方案


默认情况下,通过 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");
});

你可以使用启动 json-servernode index.js


推荐阅读