Javascript 返回模拟post响应的节点JSON服务器

Javascript 返回模拟post响应的节点JSON服务器,javascript,node.js,mocking,json-server,Javascript,Node.js,Mocking,Json Server,我尝试将其用作模拟后端,我能够为get匹配url,但如何才能为POST调用返回一些模拟响应 创建用户URL的方式如下 在某些情况下,我还希望发送自定义http代码,如500423404401等。。取决于一些数据 最大的问题是,我的代码没有为POST返回任何响应,它只是在JSON中插入记录,默认情况下,通过JSON服务器的POST请求应该会给出一个201创建的响应 如果需要自定义响应处理,可能需要一个中间件来获取req和res对象 在这里,我添加了一个中间件来拦截POST请求并发送自定义响应。你可

我尝试将其用作模拟后端,我能够为get匹配url,但如何才能为POST调用返回一些模拟响应

创建用户URL的方式如下

在某些情况下,我还希望发送自定义http代码,如500423404401等。。取决于一些数据


最大的问题是,我的代码没有为POST返回任何响应,它只是在JSON中插入记录,默认情况下,通过JSON服务器的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();
  }  
});
完整的代码(index.js)


您可以使用
node index.js

启动json服务器,您不应该根据数据返回5xx错误。5xx错误是来自web服务器的错误,它们不应该依赖于数据。在json服务器的主页上,我得到“未找到任何资源”,它无法从DB.json中检测到任何东西。应该有一个名为“DB.json”的文件与index.js文件处于同一级别。如果你需要回复。。。看这个。。有没有一种方法可以将其用于自定义路由而不是db.json?
// 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();
  }  
});
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");
});