hello i have a axios request to post data to node js server but when i try to access to this data in the server i get that it not defined .
this is the function post data:
function Submit() {
let params={
firstName:name,
lastName:lastName,
email:email,
passwordKey:pass,
statut:1
}
axios.post(`http://localhost:8080/new_user`,stringify(params))
.then((response)=>(console.log(response)))
}
this is the route in index in node js server :
app.post('/new_user',(req,res)=>{
const recived=req.body.params
console.log(recived)
/*const query = `INSERT INTO user VALUES()`;
db.query( query,function (error ,results){
if(!error ){
return res.status(201).json(results)
}
else{
//return res.status(503).json({"message":"Error in connection"})
return res.status(500).json(data)
}
})*/
})
this is the problem that i get in the server:
TypeError: Cannot read properties of undefined (reading 'params')
at C:reactjsBack-endindex.js:65:28
at Layer.handle [as handle_request] (C:reactjsBack-endnode_modulesexpresslibrouterlayer.js:95:5)
at next (C:reactjsBack-endnode_modulesexpresslibrouterroute.js:144:13)
at Route.dispatch (C:reactjsBack-endnode_modulesexpresslibrouterroute.js:114:3)
at Layer.handle [as handle_request] (C:reactjsBack-endnode_modulesexpresslibrouterlayer.js:95:5)
at C:reactjsBack-endnode_modulesexpresslibrouterindex.js:284:15
at Function.process_params (C:reactjsBack-endnode_modulesexpresslibrouterindex.js:346:12)
at next (C:reactjsBack-endnode_modulesexpresslibrouterindex.js:280:10)
at serveStatic (C:reactjsBack-endnode_modulesserve-staticindex.js:75:16)
at Layer.handle [as handle_request] (C:reactjsBack-endnode_modulesexpresslibrouterlayer.js:95:5)
3
Answers
For this issue you can write a code in index in node js by below way
This will give you exact result.
I suppose that you try to make a
JSON
content-type request. So, your axiosPOST
request is wrong. Correct it like below :A quick reminder axios automatically handles JSON.stringify when you pass the data as the second argument to the post request handler so you dont need to do JSON.stringify() again. Here is what’s happening in the request:
So you can check the result that you are receiving by logging the req.body in the nodejs backend.
So here is how to resolve the issue:
I hope this resolves your issue.