Jinshuai Ma
Jinshuai Ma

Reputation: 129

axios not sending json data

I am trying to post some json data using axios. The axios.post method works well:

axios.post(
    "http://localhost/api",
    {"k1":"v1","k2":"v2"}
)

However, the following code does not work:

const axiosInstance = axios.create({
    baseURL: 'http://localhost/api',
    method: 'POST',
    data: {"k1":"v1","k2":"v2"}
});
axiosInstance.request()

The backend is a Flask app, which cannot receive any data. It cannot even read the 'Content-type' header. So what is the difference between the above two codes? Any idea how to modify the second method so it can work?

Upvotes: 0

Views: 2104

Answers (3)

donkey
donkey

Reputation: 303

fail to receive data on backend

  let iidd = axios.create({
    baseURL: '/iidd',
    method: 'POST',
    data:{'ll': 'ok'}
  })
  iidd.request({}).then(res=>{
    console.log(res);
  })

========================================================

Can receive data on backend

  let iidd = axios.create({
    baseURL: '/iidd',
    method: 'POST'
  })
  iidd.request({data:{'ll': 'ok'}}).then(res=>{
    console.log(res);
  })

mh....In this result, maybe create axios instance couldn't have default data. but is weird, in axios doc they are [config] too, It should have same result.

Upvotes: 2

ABGR
ABGR

Reputation: 5205

You should stringify data before sending.

data: JSON.stringify({"k1":"v1","k2":"v2"})

Upvotes: 0

Aayush Mall
Aayush Mall

Reputation: 1013

The data you are trying to send is not a JSON.

{"k1":"v1","k2","v2"} should be changed to {"k1":"v1","k2":"v2"}

Upvotes: 0

Related Questions