首页 > 解决方案 > 从 fetch API 问题中获取数据

问题描述

我在前端使用了 fetch API 来发送这样的 post 请求:

fetch('accounts/google-login', {
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        method: 'post',
        body: JSON.stringify({token : id_token})
    })
    .then(response => {
        console.log('response:', response)
        response.json()
    })
    .then(result => {
        console.log("result:", result)
    })
    .catch(error => console.log(error));

代码工作正常,我可以使用这个函数在我的节点服务器中返回一个 res:

function googleLogin(req, res) {
    accountService.googleLogin(req, res)
        .then(result => {
            console.log('result Here::', result)
            res.json(result)
        })
        .catch(err => res.json(err));
}

上面的控制台日志是 在此处输入图像描述

这是我在前端控制台中得到的:

在此处输入图像描述

如您所见,我无法从googleLogin函数中获取数据(我的意思是黑色控制台中的对象),而是得到undefined了!

如何访问我发送的响应?

标签: javascriptnode.js

解决方案


您忘记return了返回值response.json()

    .then(response => {
        console.log('response:', response)
        return response.json()
//      ^^^^^^
    })

...或者没有日志记录,您可以这样写:

   .then(response => response.json())

(因为单行箭头函数隐式返回它们的结果)


推荐阅读