【问题标题】:React with Node getting json data from res.status.json()与 Node 反应,从 res.status.json() 获取 json 数据
【发布时间】:2020-02-18 03:52:20
【问题描述】:

我正在运行一个使用 nodejs 作为 api 连接到我的数据库的反应应用程序。

对于我的登录,我正在向服务器发送数据,它返回通过或失败。

但是我不确定如何提取这个 json 对象。

我查看了请求和响应,当我操作 json 对象时,响应内容长度一直在变化,所以我相信它一定在某个地方。

服务器代码:

app.post('/api/checkLogin', async (req,res) => {
    console.log(req.body);
    const {username, password} = req.body;
    try{
        let state = await DB.checkPassword(username, password);
        console.log(state);
        if(!state){
            res.status(401).json({
                error: 'Incorrect username or password',
                yay: 'idk work?'
            });
        }
        else if(state){
            res.status(200).json({
                message: 'we in boys'
            });
        } else {
            res.status(6969).json({
                err: 'idk mane'
            });
        }
    } catch(e) {
        console.log(e);
    }
})

客户代码:

    onSubmit = (event) => {
        event.preventDefault();
        fetch('/api/checkLogin', {
            method:'POST',
            body: JSON.stringify({username: this.state.username, password: md5(this.state.password)}),
            headers: {
                'Content-Type':'application/json'
            }
        }).then(res => {
            if(res.status ===200) {
                this.props.loggedIn();
            } else if(res.status ===401){
                console.log(res.status);
                alert('wrong username or password');       
            }else{
                const error = new Error(res.error);
                throw error;
            }
        }).catch(err => {
            console.log(err);
            alert(err);
        });
    }

作为一种提取数据的方式,我有点期待。

在服务器上:

res.status(200).json({ message : 'mssg'});

在客户端:

console.log(res.status.message) // 'mssg'

【问题讨论】:

    标签: javascript node.js reactjs


    【解决方案1】:

    根据我的经验,使用res.status(200).send({message: 'mssg'}) 更好。

    并且可以通过res.data调用api后获取数据。

    然后你可以得到如下结果:

    {
        message: 'mssg'
    }
    

    【讨论】:

    • 默认不会在res.send()上快速发送200状态码?
    【解决方案2】:

    感谢 Jin 和我找到的这个帖子 Fetch API get raw value from Response

    我发现两者 res.status(xxx).json({ msg: 'mssg'})res.status(xxx).send({msg: 'mssg'}) 工作。

    然后可以在客户端使用嵌套的 Promise 解释 json 或发送的消息。这是通过...完成的。

     fetch('xxx',headers n stuff).then(res => {
           res.json().then((data) => {console.log(data.message)});
           //'mssg'
           res.text().then((data) => { let data1 = JSON.parse(data); console.log(data1.message);});
           //'mssg'
    });
    

    【讨论】:

      【解决方案3】:

      这可能会有所帮助。

      onSubmit = (event) => {
      event.preventDefault();
           const userData = {
               username: this.state.username, // I like to store in object before passing in
               password: md5(this.state.password)
              }        
              fetch('/api/checkLogin', {
                  method:'POST',
                  body: JSON.stringify(userData), //stringify object
                  headers: {
                      'Content-Type':'application/json'
                  }
              }).then(res => res.json()) // convert response
              .then(responseData => {
                let status = responseData.whatObjectWasPassedFromBackEnd;
                 status === 200 ? do something on pass:  do something on fail
              })
              .catch(err => {
                  console.log(err);
                  alert(err);
              });
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-28
        • 1970-01-01
        • 1970-01-01
        • 2020-05-29
        • 2021-07-10
        • 2021-05-23
        • 1970-01-01
        • 2017-05-11
        相关资源
        最近更新 更多