Reputation: 1328
I am trying to send the data from input boxes in react server to nodejs server but everytime i am getting error on backend
TypeError: Cannot read property 'email' of undefined
Here is my code for that
onformsubmit=()=>{
console.log(this.state.email,this.state.password) ///gets printed correctly
axios.post('http://localhost:5000/acc-details',{
email:this.state.email,
password:this.state.password
})
.then(response=>{
console.log('success')
})
.catch(err=>console.log(err))
}
and then in node server
const express=require('express')
const app=express()
var bodyparser=require('body-parser')
app.use(bodyparser.json())
router.post('/acc-details',(req,res)=>{
console.log(req.body.email)
res.send('ok')
})
if not consoling in node server i am getting response back 'ok' as writtten above but i want to fetch my email and password on node server for db authentication
Upvotes: 3
Views: 147
Reputation: 584
onformsubmit=()=>{
console.log(this.state.email,this.state.password) ///gets printed correctly
axios({
url: 'http://localhost:5000/acc-details'
method: 'POST',
data: { email: this.state.email, password: this.state.password }
})
.then(response=>{
console.log('success')
})
.catch(err=>console.log(err))
}
Now you should be able to access req.body
Edit:
after 200 tries, i figured out:
axios({
url: "http://localhost:5000/acc-details",
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
},
data: { email: this.state.email, password: this.state.password }
});```
Upvotes: 0
Reputation: 9782
Modify your Axios request slightly to send multipart/form-data data.
onformsubmit = () => {
// Collect properties from the state
const {email, password} = this.state;
// Use FormData API
var formdata = new FormData();
formdata.append('email', email);
formdata.append('password', password);
axios.post('http://localhost:5000/acc-details', formdata)
.then( response=> {
console.log('success')
})
.catch(err=>console.log(err))
}
Upvotes: 1