【问题标题】:Sending data back from node server back to react frontend从节点服务器发回数据以响应前端
【发布时间】:2019-01-18 04:25:35
【问题描述】:

我正在尝试使用 react 和 node 为主页创建登录名,其中包含来自硬编码数据库的用户详细信息。节点后端识别json密码和邮箱,但获取不到代码将数据发回前端登录。

我已经使用邮递员测试了后端,以确保我可以获取数据。

节点服务器

    app.post('/signin', (req, res) => { 
      if(req.body.email === database.users[0].email &&
        req.body.password === database.users[0].password) {

        res.json('success');  
      }
      else {
        res.status(400).json('error logging in');
      }
    })

反应

    class Signin extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
       signInEmail: '',
       signInPassword: ''
      }
    }

    onSubmitSignIn = () => {
      fetch('http://localhost:5000/signin', {
        method: 'post',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
        email: this.state.signInEmail,
        password: this.state.signInPassword
      })
     })
      .then(user => {
        if (user.id) {
          this.props.loadUser(user)
          this.props.onRouteChange('home');
        }
      })
     }

数据库

    const database = {
      users: [
        {
          id: '123',
          name: 'andrew',
          email: 'andrew@outlook',
          password: 'p',
          entries: 0,
          joined: new Date()
        },
        {
          id: '124',
          name: 'sally',
          email:' sally@outlook',
          password: 'bananas',
          entries: 0,
          joined: new Date()
        },
      ],
    }

当我删除.then(user =>) 呼叫并直接转到this.props.onRouteChange('home') 时它可以工作,但否则会保留在登录页面上。这让我发疯了,任何帮助表示赞赏。

【问题讨论】:

    标签: node.js reactjs express


    【解决方案1】:

    欢迎使用 stackoverflow!

    我认为您没有将正确的数据发送回前端或检查错误的数据。

    您的 nodeJS 应用程序发送任一

    res.json('success'); 
    

    res.status(400).json('error logging in');
    

    所以无论你发回什么字符串。但是在前端,您正在检查响应中的 id 属性:

    .then(user => {
      if (user.id) {
        this.props.loadUser(user)
        this.props.onRouteChange('home');
      }
    })
    

    您的user 是您在fetch 之后获得的响应对象。如果您将user 重命名为response 并调用response.json(),您可以添加另一个.then(json => {...},您可以在其中检查您的json 对象是否是您的nodeJS 后端发送的字符串之一。

    【讨论】:

    • 您好,感谢您的欢迎,作为读者,两年来一直使用堆栈,它让我多次摆脱困境。也感谢您的回复。你是对的。我将其更改为:if(response.json === 'success') { this.props.onRouteChange('home'); } 我只是深深地沉浸在其中,以至于我没有推理它并且需要其他人指出它。不幸的是,无法登录的问题仍然存在 - 我认为与 Cors 有关,这是另一个问题
    • 总是乐于提供帮助。好吧,我认为如果登录问题仍然存在,您真的应该创建一个新问题,其中包含您的 this.props.loadUser(user) 代码和与之相关的代码。
    猜你喜欢
    • 2022-06-21
    • 2021-10-06
    • 1970-01-01
    • 2016-01-12
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多