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
Sending a PUT Request with Axios The simplest way to make the PUT call is to simply use the put() function of the axios instance, and supply the body of that request in the form of a JavaScript object: const res = await axios. put('/api/article/123', { title: 'Making PUT Requests with Axios', status: 'published' });
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.
Axios' post() function supports a data parameter that becomes the HTTP request body. On the other hand, axios. get() does not support this parameter.
To send an Axios POST request with headers, you need to use the headers option. With axios. post() , the first parameter is the URL, the 2nd parameter is the request body, and the 3rd parameter is the options . For example, below is how you set the Content-Type header on an HTTP POST request.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With