101

I am trying to communicate with an API from my React application using Axios. I managed to get the GET request working, but now I need a POST one.

I need the body to be raw text, as I will write an MDX query in it. Here is the part where I make the request:

axios.post(baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
    {
      headers: { 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxx',
      'Content-Type' : 'text/plain' }
    }).then((response) => {
      this.setState({data:response.data});
      console.log(this.state.data);
    });

Here I added the content type part. But how can I add the body part?

Thank you.

Edit:

Here is a screenshot of the working Postman request Postman working request

Ogglas
  • 62,132
  • 37
  • 328
  • 418
Karim Taha
  • 1,151
  • 3
  • 9
  • 14

14 Answers14

111

How about using direct axios API?

axios({
  method: 'post',
  url: baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
  headers: {}, 
  data: {
    foo: 'bar', // This is the body part
  }
});

Source: axios api

Ukasha
  • 2,238
  • 3
  • 21
  • 30
69

You can use postman to generate code. Look at this image. Follow step1 and step 2.

enter image description here

If your endpoint just accepts data that have been sent with Body (in postman), You should send FormData.

var formdata = new FormData();
//add three variable to form
formdata.append("imdbid", "1234");
formdata.append("token", "d48a3c54948b4c4edd9207151ff1c7a3");
formdata.append("rate", "4");
      
let res = await axios.post("/api/save_rate", formdata);
Avi Cohen
  • 117
  • 5
reza jafari
  • 1,228
  • 13
  • 14
  • 10
    I was coming to this post to help with an answer, and i just learned something new.. i never noticed or even clicked the code snippet button, and i've been using postman for more than i can remember.. +1 – Dany Balian Dec 29 '21 at 22:34
  • 1
    The best solution, works for every situation, thank you :pray: – Naeem Baghi May 05 '23 at 16:45
  • 1
    Never knew postman could generate code. This was a savior for me. Thanks a ton – Shreehari Jun 29 '23 at 07:34
31

You can use the below for passing the raw text.

axios.post(
        baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan, 
        body, 
        {
            headers: { 
                'Authorization': 'Basic xxxxxxxxxxxxxxxxxxx',
                'Content-Type' : 'text/plain' 
            }
        }
).then(response => {
    this.setState({data:response.data});
    console.log(this.state.data);
});

Just have your raw text within body or pass it directly within quotes as 'raw text to be sent' in place of body.

The signature of the axios post is axios.post(url[, data[, config]]), so the data is where you pass your request body.

Armand
  • 2,611
  • 2
  • 24
  • 39
Madhu Bhat
  • 13,559
  • 2
  • 38
  • 54
12

The key is to use "Content-Type": "text/plain" as mentioned by @MadhuBhat.

axios.post(path, code, { headers: { "Content-Type": "text/plain" } }).then(response => {
    console.log(response);
});

A thing to note if you use .NET is that a raw string to a controller will return 415 Unsupported Media Type. To get around this you need to encapsulate the raw string in hyphens like this and send it as "Content-Type": "application/json":

axios.post(path, "\"" + code + "\"", { headers: { "Content-Type": "application/json" } }).then(response => {
    console.log(response);
});

C# Controller:

[HttpPost]
public async Task<ActionResult<string>> Post([FromBody] string code)
{
    return Ok(code);
}

https://weblog.west-wind.com/posts/2017/sep/14/accepting-raw-request-body-content-in-aspnet-core-api-controllers

You can also make a POST with query params if that helps:

.post(`/mails/users/sendVerificationMail`, null, { params: {
  mail,
  firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));

This will POST an empty body with the two query params:

POST http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName

Source: https://stackoverflow.com/a/53501339/3850405

Ogglas
  • 62,132
  • 37
  • 328
  • 418
9

Here is my solution:

axios({
  method: "POST",
  url: "https://URL.com/api/services/fetchQuizList",
  headers: {
    "x-access-key": data,
    "x-access-token": token,
  },
  data: {
    quiz_name: quizname,
  },
})
.then(res => {
  console.log("res", res.data.message);
})
.catch(err => {
  console.log("error in request", err);
});

This should help

TheZ
  • 3,663
  • 19
  • 34
Adnan
  • 1,589
  • 11
  • 17
5

You can pass the params like so

await axios.post(URL, {
  key:value //Second param will be your body
},
{
headers: {
  Authorization: ``,
  'Content-Type': 'application/json'
}

this makes it easier to test/mock in Jest as well

Jeffery Sidhu
  • 109
  • 1
  • 8
  • -1 What in your answer is different to that of @Uddesh_jain (except for the `Authorization` header which does not count, as it is already in the question)? – Tino Mar 23 '21 at 08:13
4

I got same problem. So I looked into the axios document. I found it. you can do it like this. this is easiest way. and super simple.

https://www.npmjs.com/package/axios#using-applicationx-www-form-urlencoded-format

var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

You can use .then,.catch.

hahaha
  • 1,379
  • 4
  • 11
  • 22
3

For sending form data in the body, you can just format the data in url params like this 'grant_type=client_credentials&client_id=12345&client_secret=678910' and attached it to data in the config for axios.

axios.request({
    method: 'post',
    url: 'http://www.example.com/',
    data: 'grant_type=client_credentials&client_id=12345&client_secret=678910',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
    },
})
s-hunter
  • 24,172
  • 16
  • 88
  • 130
2

The only solution I found that would work is the transformRequest property which allows you to override the extra data prep axios does before sending off the request.

    axios.request({
        method: 'post',
        url: 'http://foo.bar/',
        data: {},
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        transformRequest: [(data, header) => {
            data = 'grant_type=client_credentials'
            return data
        }]
    })
Query
  • 720
  • 2
  • 7
  • 23
  • Thanks for sharing the transformRequest option. I am testing an API and wanted to deliberately send broken JSON data to the server. Your answer brought me to the correct solution. – line-o Aug 13 '22 at 16:31
2

This worked fine for me when trying to send authentication credential in body in raw json format.

let credentials = {
  username: "your-username",
  password: "your-password",
};
axios
.get(url, { data: credentials })
.then((res) => {
  console.log(res.data);
})
Atiq Baqi
  • 612
  • 1
  • 7
  • 16
2

Used in React js

let url = `${process.env.REACT_APP_API}/validuser`;

   let body = JSON.stringify({
     loginid: "admin",
     password: "admin",
  });

var authOptions = {
  method: "post",
  url: url,
  data: body,
  headers: {
    "Content-Type": "application/json",
  },
  json: true,
};

axios(authOptions)
  .then((resp) => {
    console.log("response :- ",resp);
  })
  .catch((error) => {
    alert(error);
  });
Deepak Singh
  • 749
  • 4
  • 16
0
axios({
  method: 'post',     //put
  url: url,
  headers: {'Authorization': 'Bearer'+token}, 
  data: {
     firstName: 'Keshav', // This is the body part
     lastName: 'Gera'
  }
});
Keshav Gera
  • 10,807
  • 1
  • 75
  • 53
  • 2
    It helps more if you supply an explanation why this is the preferred solution and explain how it works. We want to educate, not just provide code. – the Tin Man Feb 05 '20 at 21:30
  • 4
    Data part is sent as JSON here and not a simple string – Ogglas Aug 13 '20 at 10:11
0

There many methods to send raw data with a post request. I personally like this one.

    const url = "your url"
    const data = {key: value}
    const headers = {
        "Content-Type": "application/json"
    }
    axios.post(url, data, headers)
Uddesh Jain
  • 1,064
  • 2
  • 15
  • 16
0

   

 let url='<your domain.extension>';
 let data= JSON.stringify('mydata');
 axios
 .get(url, { data })
 .then((res) => {
     console.log(res.data);
  })

For me this solution works, i.e. JSON.stringify(your data) , just convert your raw data using JSON.stringify method.

I hope this works.