【问题标题】:Node JSON-Server returning MOCK post response节点 JSON-Server 返回 MOCK 发布响应
【发布时间】:2020-02-06 09:27:04
【问题描述】:

我正在尝试使用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 中插入记录

【问题讨论】:

  • 您不应根据数据返回 5xx 错误。 5xx 错误是来自网络服务器的错误,它们不应依赖于数据。

标签: javascript node.js mocking json-server


【解决方案1】:

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

【讨论】:

  • 在 json-server 的主页上,localhost:3000 我得到“找不到资源”,它无法从 DB.json 中检测到任何东西
  • 与index.js文件同级应该有一个名为“db.json”的文件。如果你需要一个 repl... 看到这个.. repl.it/repls/PleasedImperfectScientificcomputing
  • 有没有办法使用自定义路由而不是 db.json?
猜你喜欢
  • 1970-01-01
  • 2019-08-24
  • 1970-01-01
  • 1970-01-01
  • 2017-12-30
  • 1970-01-01
  • 2019-07-28
  • 1970-01-01
相关资源
最近更新 更多