16
votes

I am using Axios JS library for sending post json request. but I am not receiving anything at the server. Here is my code

const dt = JSON.stringify({"data":{"value":"gdfg1df2g2121dgfdg"}});
const request = axios.post(url, {dt});

I need to send post raw body in json format.

3
What are the headers you are sending ? - Karthik VU
not sending any headers. I tested the server with postman and without any headers, server is working ok. - h_h
Not sure with this, but try const request = axios.post('https://api.medlanes.com/booking_center/call/get_products', dt); - Karthik VU
yup, worked.... - h_h

3 Answers

13
votes

By default axios uses Json for posting data so you don't need to stringify your data. The problem could be that you're doing that. Could you try doing the post without it and check if it works? Also you don't need the curly braces to wrap your data unless that's the format of the object in your server. Otherwise could you give me information about how the body of the request looks like so I have more context? You can check that in chrome dev tools using the network tab

6
votes

You don't need to stringify your payload. Axios will do it for you when it it send a request.

const dt = { data: { value: "gdfg1df2g2121dgfdg" }};
const request = axios.post(url, dt);
-2
votes

Axios for post request with json as its body:

  static async postService(path, data = {}) {
    const requestUrl = HttpRequest._getRequestUrl(path);

    try {
      const ret = await axios.post(requestUrl, JSON.stringify(data));
      console.log('Request result ', ret);
    } catch (error) {
      console.error(`Request error: ${error.message}`);
    }
  }