3

how can I something like this, sending body params and header with Authorization token into this

enter image description here

const searchByDate = async ({ date1, date2 }) => {
  const tokenApp = window.localStorage.getItem('token');
  const { data: res } = await axios.get(`${baseUrl}/search`, {
    data: { date1: date1, date2: date2 },
    headers: { Authorization: `${tokenApp}` },
  });
  return res;
};

so far it is throwing me an error Required request body is missing

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Jose A.
  • 483
  • 2
  • 7
  • 15
  • Does this answer your question? [Sending Request body for GET method in AXIOS throws error](https://stackoverflow.com/questions/54005520/sending-request-body-for-get-method-in-axios-throws-error) – Quentin Dec 22 '21 at 08:05

2 Answers2

3

In general there is no point in a body for GET requests, so axios does not support it.

If you read the axios config documentation, you will find

// data is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'

You can read more at HTTP GET with request body for the reasons.


If you want to send data in a GET request use the params property

// params are the URL parameters to be sent with the request
// Must be a plain object or a URLSearchParams object

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
0

There is no field related to body in get method in axios you can transfer data by get the data in query in URL like this:

const searchByDate = async ({ date1, date2 }) => {
  const data = { date1: date1, date2: date2 }
  const tokenApp = window.localStorage.getItem('token');
  const { data: res } = await axios.get(`${baseUrl}/search?data=${JSON.stringify(data)}`, {
    headers: { Authorization: `${tokenApp}` },
  });
  return res;
};

in backend to convert the data from string to original data types just wrap the data in

JSON.parse(data)
Mahmoud Kandel
  • 140
  • 1
  • 5