将数据从反应服务器发送到节点服务器

时间:2019-11-30 08:10:45

标签: node.js reactjs express

我正在尝试将数据从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”,但我想在节点服务器上获取我的电子邮件和密码以进行数据库身份验证

2 个答案:

答案 0 :(得分:1)

稍微修改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))
}

答案 1 :(得分:0)

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

现在您应该可以访问req.body


编辑:

经过200次尝试,我发现:

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