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
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))
}
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 }
});```
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.