我正在尝试将数据从React服务器中的输入框发送到NodeJS服务器,但是每次我在后端遇到错误时

TypeError: Cannot read property 'email' of undefined


这是我的代码

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))
}


然后在节点服务器中

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')
})


如果不安慰节点服务器,我会像上面写的那样返回响应“ ok”,但是我想在节点服务器上获取我的电子邮件和密码以进行数据库身份验证

最佳答案

略微修改您的Axios请求以发送多部分/表单数据数据。

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))
}

07-28 03:12
查看更多