【问题标题】:Sending data from react server to node server将数据从反应服务器发送到节点服务器
【发布时间】:2019-11-30 08:10:45
【问题描述】:

我正在尝试将数据从反应服务器中的输入框发送到 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')
})

如果没有在节点服务器中进行安慰,我会收到上面写的回复“好的”,但我想在节点服务器上获取我的电子邮件和密码以进行数据库身份验证

【问题讨论】:

  • 你在这里有router.post('...'),但你把bodyparser.json()放在app.use()上。错字?如果不是,请将router. 更改为app.
  • 最好用postman之类的工具来测试你的服务器,以确定你的服务器代码是有问题还是前端。

标签: node.js reactjs express


【解决方案1】:

稍微修改您的 Axios 请求以发送 multipart/form-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))
}

【讨论】:

  • 它说formdata没有在服务器端定义:(
  • @Ratnabhkumarrai 确保你已经在客户端实现了这个,formdata 不应该被服务器端访问。
  • 我应该在服务器上控制台检查什么?
【解决方案2】:
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 }
    });```

【讨论】:

  • 在服务器端 console.log(req.body.data) ??
  • console.log(req.body.email, req.body.password)
  • 但是我也遇到了与以前相同的错误
  • console.log(req.body) 的输出是什么?
  • 未定义老兄!
猜你喜欢
  • 1970-01-01
  • 2020-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-04
  • 2020-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多