shamgar
shamgar

Reputation: 120

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

Upvotes: 0

Views: 1451

Answers (1)

shamgar
shamgar

Reputation: 120

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());

Upvotes: 1

Related Questions