Joey Yi Zhao
Joey Yi Zhao

Reputation: 42418

How to use `axios` post a raw data

I have a backend rest API which accept post request. I am able to send post request to the API through postman with below settings:

Method: POST
Header: Content-Type: application/json
Body: raw
      {"date": "2018-08-18"}

but I got 405 method not allow error with below axios code.

axios
      .post(
        url,
        JSON.stringify({
          date: "2018-08-18"
        }),
        {
          headers: {
            "Content-Type": "application/json"
          }
        }
      )

If I remove the headers I will get 400 error code as below:

axios
          .post(
            url,
            JSON.stringify({
              date: "2018-08-18"
            })
          )

I also tried to remove stringify but it still doesn't work. I got 405 response:

axios
              .post(
                url,
                {
                  date: "2018-08-18"
                },
                {
                  headers: {
                    "Content-Type": "application/json"
                  }
                }
              )

It is probably because of the body message. Is there a way for me to use axios to send the raw json data?

Upvotes: 5

Views: 15880

Answers (1)

Anurag Awasthi
Anurag Awasthi

Reputation: 6223

You dont need to do stringify the body, axios will do that for you.

axios.post(url,{
  date: "2018-08-18"
}, {
  headers: {
    "Content-Type": "application/json"
  }
})

Upvotes: 9

Related Questions