【问题标题】:How to get a return value from a post request in NextJs 9 Serverless如何从 NextJs 9 Serverless 中的发布请求中获取返回值
【发布时间】:2020-04-19 02:35:57
【问题描述】:

我正在使用 NextJs 构建一个无服务器应用程序,但我不知道如何在向我的数据库发出发布请求时获取包含用户 JWT 的返回值。一切都按预期进行,但我无法解决这一问题。

在我的登录页面中,这是我处理用户提交数据的方式:

const res = await fetch(`${process.env.BASE_URL}/api/login`, {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify(userInfo)
})

console.log('successfully logged in')
console.log(res)

在我的 API 中,我向/api/login 发出请求时返回值的方式是:

return res.status(201).json({
  message: 'Account successfully signed in!',
  user,
  token
})

现在,当我在开发工具中检查我的 console.log 时,响应如下所示:

type: "basic"
url: "http://localhost:3000/api/login"
redirected: false
status: 200
ok: true
statusText: "OK"
headers: Headers {}
body: ReadableStream
locked: false
__proto__: ReadableStream
bodyUsed: false
__proto__: Response

那里什么都没有,我不知道为什么?

【问题讨论】:

  • 您没有在 POST 请求中发送任何 jwt
  • 正确,当用户登录时,我想生成一个JWT服务器端并将其发送回客户端。

标签: authentication post return-value next.js serverless


【解决方案1】:

这是一个 fetch 正文响应,您应该按照您期望的类型对其进行解码(在您的情况下为 json)。

const res = await fetch(`${process.env.BASE_URL}/api/login`, {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify(userInfo)
})
const data = await res.json(); // <--- this is the missing part

console.log('successfully logged in')
console.log(data)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2020-07-18
    • 1970-01-01
    相关资源
    最近更新 更多