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
CodePudding user response:
I guess you want to send data to backend. You can do it this way.
await api.post("/",data);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Or
await axios.post('/', {
data: { //here },
});
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
If again body format is all wrong maybe you can try this.
JSON.parse(JSON.stringify(req.body));
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
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());