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

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

This question is related to javascript c# reactjs post axios

The answer is


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.


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

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


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


axios({
  method: 'post',     //put
  url: url,
  headers: {'Authorization': 'Bearer'+token}, 
  data: {
     firstName: 'Keshav', // This is the body part
     lastName: 'Gera'
  }
});

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.


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)

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to post

How to post query parameters with Axios? How can I add raw data body to an axios request? HTTP POST with Json on Body - Flutter/Dart How do I POST XML data to a webservice with Postman? How to set header and options in axios? Redirecting to a page after submitting form in HTML How to post raw body data with curl? How do I make a https post in Node Js without any third party module? How to convert an object to JSON correctly in Angular 2 with TypeScript Postman: How to make multiple requests at the same time

Examples related to axios

How to post query parameters with Axios? Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check How can I add raw data body to an axios request? Axios Delete request with body and headers? Axios having CORS issue Axios handling errors Returning data from Axios API axios post request to send form data Change the default base url for axios Access Control Origin Header error using Axios in React Web throwing error in Chrome