首页 > 解决方案 > 与 Node 反应,从 res.status.json() 获取 json 数据

问题描述

我正在运行一个使用 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'

标签: javascriptnode.jsreactjs

解决方案


感谢 Jin 和我找到的这篇文章帮助Fetch API 从响应中获取原始值

我发现两者都 res.status(xxx).json({ msg: 'mssg'})有效res.status(xxx).send({msg: 'mssg'})

然后可以使用嵌套的承诺在客户端解释 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'
});

推荐阅读