Json-server: Is there a way to accept POST, PUT etc but not override json content, and also respond with said content?

Created on 5 Jul 2017  路  4Comments  路  Source: typicode/json-server

Consider the following scenario:

To mock a fetch request (method POST) to endpoint "/login" which returns { "userID": 123, "token": "token" }. The purpose is to mock an API endpoint only, ignoring submitted params, and returning the defined json.

Currently, the POST request will replace the expected response with the fields in the request body, removing the expected response from that API call. I.e:

A. Before the POST request:

{
    "login": {
        "userID": 123,
        "token": "token"
    }
}

B. After the POST request:

{
    "login": {
        "username": "[email protected]",
        "password": "secretpassword"
    }
}

The ideal scenario in this case is to define json in A, accept a POST method, and return json in A.

This can be somewhat achieved by using a .js file, but .js doesn't work with --watch.

Let me hear your thoughts, or please let me know if there's already a way to achieve the above that I've missed from the API reference docs.

Most helpful comment

It seems like the only way is write a middleware that changes requests from POST/PUT to GET:

server.use((req, res, next) => {
  if (req.method === 'POST') {
    req.method = 'GET';
  }
  next();
});

You can still have and react to POST requests if you do this BEFORE the middleware:

server.post('/addUser', (req, next) => {
  res.jsonp(myResponse);
});

server.use((req, res, next) => {
  if (req.method === 'POST') {
    req.method = 'GET';
  }
  next();
});

All 4 comments

same question.

This is how I thought it would work. Any chance we can get an option to always respond with the json?

It seems there is a workaround detailed in this issue #453

It seems like the only way is write a middleware that changes requests from POST/PUT to GET:

server.use((req, res, next) => {
  if (req.method === 'POST') {
    req.method = 'GET';
  }
  next();
});

You can still have and react to POST requests if you do this BEFORE the middleware:

server.post('/addUser', (req, next) => {
  res.jsonp(myResponse);
});

server.use((req, res, next) => {
  if (req.method === 'POST') {
    req.method = 'GET';
  }
  next();
});
Was this page helpful?
0 / 5 - 0 ratings

Related issues

shikaan picture shikaan  路  3Comments

0plus1 picture 0plus1  路  3Comments

sharpmachine picture sharpmachine  路  4Comments

jasonlimantoro picture jasonlimantoro  路  4Comments

bahmutov picture bahmutov  路  3Comments