简体   繁体   中英

axios post request body is wrong

I'm trying to connect my react app to my node api. I managed to get data, but when I try to post data, the body format is all wrong. I followd the axios docs .

this is my code:

import Axios from "axios";

const api = Axios.create({
  baseURL: "http://localhost:8000",
  timeout: 1000,
  headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});


await api.post("/",{data:"someData"});
    populateData(); // a function that gets data from server

when I log the req.body in the server, this is what I get

{ '{"data":"someData"}': '' }

When I didn't set any header, the body was empty. So with a little research I tried to put other types of headers but didn't find solutions

I guess you want to send data to backend. You can do it this way.

 await api.post("/",data);

Or

 await axios.post('/', { data: { //here }, });

If again body format is all wrong maybe you can try this.

 JSON.parse(JSON.stringify(req.body));

the solution was at the express config. I didn't add a middleware to parse json requests, only urlencoded ones.

once I added this code to express, and set config type to application-json it worked

app.use(express.json());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM