javascript - 从 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
了!
如何访问我发送的响应?
解决方案
您忘记return
了返回值response.json()
:
.then(response => {
console.log('response:', response)
return response.json()
// ^^^^^^
})
...或者没有日志记录,您可以这样写:
.then(response => response.json())
(因为单行箭头函数隐式返回它们的结果)
推荐阅读
- python - 使用带有默认条件的 sklearn2pmml 将决策树转换为 PMML
- ssh - 使用 ZeroTier 网络的 SSH 隧道
- visual-studio-code - VS Code - 有没有办法计算项目中的所有代码行?
- amazon-web-services - AWS 加载客户端凭证
- karate - 服务虚拟化 - 空手道
- css - 如何将 flexbox 项目从移动设备上的单列重新排序到桌面上的列和行
- javascript - 从 DOM 中删除脚本创建的 div
- shopify - 如何查询或导出所有 Shopify 客户或具有速率限制的订单
- c# - 在数据网格中显示按钮
- azure - 使用个人访问令牌部署 Azure Function