Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending data from react server to node server

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

like image 813
Ratnabh kumar rai Avatar asked Sep 14 '26 20:09

Ratnabh kumar rai


1 Answers

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))
}
like image 154
jogesh_pi Avatar answered Sep 17 '26 20:09

jogesh_pi