【问题标题】:Understanding Post request responses in React理解 React 中的 Post 请求响应
【发布时间】:2021-11-15 01:26:53
【问题描述】:

在我的 React 应用程序中,我向我创建的 ASP.Net Core Web API 发出了一个发布请求:

fetch('https://localhost:44326/api/Players/post', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        handle: data.handle,
        role: data.role,
        avatar: linkToAvatar,
      }),
    }).then((response) => console.log(response.body));

这个 post 方法成功执行,新记录被添加到数据库中。但是,我需要刚刚创建的玩家记录的 ID。

如果我在 Postman 中向这个地址发出这个帖子请求:https://localhost:44326/api/Players/post with body

{
  "handle": "Cole",
  "role": "Fixer",
  "avatar": "null"
}

它发回这个响应正文

{
    "id": 58,
    "handle": "Cole",
    "role": "Fixer",
    "avatar": "null",
    "specialAbilities": null,
    "stats": null
}

这正是我想要在 React 中得到的。

正如您在我的 fetch 方法中看到的,我正在尝试访问它:

.then((response) => console.log(response.body));

但是 response.body 看起来不像 Postman 中的那样。相反,它看起来像这样:

ReadableStream {locked: false}
locked: false
[[Prototype]]: ReadableStream
cancel: ƒ cancel()
getReader: ƒ getReader()
locked: (...)
pipeThrough: ƒ pipeThrough()
pipeTo: ƒ pipeTo()
tee: ƒ tee()
constructor: ƒ ReadableStream()
Symbol(Symbol.toStringTag): "ReadableStream"
get locked: ƒ locked()
[[Prototype]]: Object
constructor: ƒ Object()
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
propertyIsEnumerable: ƒ propertyIsEnumerable()
toLocaleString: ƒ toLocaleString()
toString: ƒ toString()
valueOf: ƒ valueOf()
__defineGetter__: ƒ __defineGetter__()
__defineSetter__: ƒ __defineSetter__()
__lookupGetter__: ƒ __lookupGetter__()
__lookupSetter__: ƒ __lookupSetter__()
__proto__: (...)
get __proto__: ƒ __proto__()
set __proto__: ƒ __proto__()

编辑:根据第一条评论,我试过这个:

如果我尝试console.log(response.json()));,它会给我这个:

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object
avatar: "https://cyberpunkv2.s3.us-east-2.amazonaws.com/avatars/cyberpunk-logo-3.jpeg"
handle: "Iggy Dog Yo"
id: 61
role: "Rockerboy"
specialAbilities: null
stats: null
[[Prototype]]: Object

所以在这里我可以看到我需要的 ID,但我怎样才能获得该 ID 以将其分配给变量?

【问题讨论】:

标签: reactjs post asp.net-web-api postman fetch-api


【解决方案1】:

我想通了。我确信有一种更优雅的方法可以做到这一点,但我这样做了:

      console.log(response.json().then((data) => setNewID(data.id)))

并且能够将NewID 设置为正确的ID。

【讨论】:

    猜你喜欢
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2020-11-17
    相关资源
    最近更新 更多