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

前端 未结 8 1153
情歌与酒
情歌与酒 2020-12-30 19:44

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

8条回答
  •  时光取名叫无心
    2020-12-30 19:59

    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> 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

提交回复
热议问题