Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

How can I add raw data body to an axios request?

Writer Matthew Harrington

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 requestPostman working request

0

11 Answers

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

2

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", dataform);
1

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.

3

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);
}

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

Source:

0

Here is my solution:

axios({ method: "POST", url: "", 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

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

1

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.

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

You can use .then,.catch.

0

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: ' data: 'grant_type=client_credentials&client_id=12345&client_secret=678910', headers: { 'Content-Type': 'application/x-www-form-urlencoded', },
})
axios({ method: 'post', //put url: url, headers: {'Authorization': 'Bearer'+token}, data: { firstName: 'Keshav', // This is the body part lastName: 'Gera' }
});
2

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)

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: ' data: {}, headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, transformRequest: [(data, header) => { data = 'grant_type=client_credentials' return data }] })

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy