0

My data (id: 12) is on the req.query and I don't know how can I pass the data on the body of the request. I know that I can use '/getUsers/12' but I need on body because in other endpoints I will use more data and I need do the same I describe here.

When I test my endpoints on insomnia all works perfect receiving data on req.body, but when I try with ajax, the req.body is empty and the data is on req.query.

I have seen this answer (jQuery posting valid json in request body) but not help me or I am missing something.

My endpoint

router.get('/getUsers', async (req, res) => {
  let operationRes = new OperationResponse();
  if (req.body.id) {
    try {
      const data = await indexService.getUsers(model.models, req.body.id);
      operationRes.addResult(data);
    }
    catch (err) {
      operationRes.addError(err);
    }
  } else {
    operationRes.addError('Parameter id is missing.');
  }
  res.send(operationRes);
});

My ajax call:

const headers = {
  'contentType': "application/json",
  'clientid': '',
  'clientsecret': '',
};
const registers = await $j.ajax({
    url: 'http://localhost:3001/getUsers',
    type: "GET",
    headers,
    data: { "id": 12 },
    dataType: 'json'
  });
  console.log(registers);
});
Philippe
  • 31
  • 7
  • 2
    Use another HTTP method than GET. Adding a body to a get request is discouraged by the HTTP spec and not widely supported – Jonas Høgh May 06 '21 at 14:05
  • Thanks @JonasHøgh I thought I was missing something to do that, but the better solution was change how I handle with the requests, taking data from req.query. – Philippe May 06 '21 at 16:29

0 Answers0