Узел JSON-сервер возвращает MOCK после ответа - PullRequest
0 голосов
/ 09 октября 2019

Я пытаюсь использовать 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

1 Ответ

1 голос
/ 09 октября 2019

По умолчанию запросы 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");
});

И вы можете запустить json-сервер, используя node index.js

...