React 使用 Fetch 请求 API 返回响应 [object Object]?

huangapple go评论72阅读模式
英文:

React Fetch post api return response [object Object]?

问题

const App = () => {
  const [userInfo, setuserInfo] = useState('');
  useEffect(() => {
    const url = 'https://test.com/v1/getSessionInfoById';
    const requestOptions = {
      method: 'POST',
      headers: { 'Content-type': 'application/json' },
      body: JSON.stringify({ sessionId: 'cf209972-51d6-37d5-b9e9' })
    };
    const fetchData = async () => {
      try {
        const response = await fetch(url, requestOptions);
        const json = await response.json();
        console.log("json " + JSON.stringify(json));
        setuserInfo(json);
      } catch (error) {
        console.log("error", error);
      }
    };
    fetchData();
  }, []);

  return (
    <>{JSON.stringify(userInfo)}</>
  )
};

export default App;
英文:

I am working on react. I have an api that is using POST method, body contains sessionId and returns response data in json. In postman, it's working fine. But in React, its returning [object Object]. Method is post, but api is getting the data. Please let me know what's the issue why console.log(&quot;json &quot; + json) is giving [object Object]

const App = () =&gt; {
  const [userInfo, setuserInfo] = useState(‘’);
  useEffect(() =&gt; {
    const url = &#39;https://test.com/v1/getSessionInfoById&#39;;
    const requestOptions = {
      method: &#39;POST&#39;,
      headers: { &#39;Content-type&#39;: &#39;application/json&#39; },
      body: JSON.stringify({ sessionId: &#39;cf209972-51d6-37d5-b9e9&#39; })
    };
    const fetchData = async () =&gt; {
      try {
        const response = await fetch(url, requestOptions);
        const json = await response.json();
        console.log(&quot;json &quot; + json);
        setuserInfo(json);
      } catch (error) {
        console.log(&quot;error&quot;, error);
      }
    };
    fetchData();
  }, []);

  return (
    &lt;&gt;userInfo&lt;/&gt;
  )
};

export default App;

Postman response is

{
    &quot;sessionId&quot;: &quot;cf209972-51d6-37d5-b9e9&quot;,
    &quot;userId&quot;: &quot;114&quot;,
    &quot;expirationDate&quot;: &quot;2023-04-21&quot;,
    &quot;keyPropertiesList&quot;: [
        {
            &quot;id&quot;: 266277,
            &quot;properties&quot;: {
                &quot;user&quot;: {
                    &quot;firstName&quot;: &quot;test&quot;,
                    &quot;lastName&quot;: &quot;A&quot;,
                    &quot;fullName&quot;: &quot;test A&quot;
                },

                &quot;userDetail&quot;: {
                    &quot;phoneNo&quot;: &quot;666-777-9999&quot;,
                    &quot;email&quot;: &quot;test@test.com&quot;
                },
                &quot;locationID&quot;: &quot;78&quot;
            }
        }
    ]
}

答案1

得分: 1

The api is giving the correct answer however, you are wrongly printing it.

const js = { name: "sachin" }
console.log("json", js)

Look at this code once, I wrote the right json but still it says [Object Object] because I'm printing in the console with , operator as: console.log("json", js)
Because you are not concatenating here, you are just printing those values.

英文:

The api is giving the correct answer however, you are wrongly printing it.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const js = { name : &quot;sachin&quot; }
console.log(&quot;json&quot; + js )

<!-- end snippet -->

look at this code once, I wrote the right json bt still it says [Object Object] because I'm printing in the console with + operator as : console.log(&quot;json&quot; + js )
Because you are trying to concatenate a string with an object.

however replacing + with , will give the correct answer.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const js = { name : &quot;sachin&quot; }
console.log(&quot;json&quot; , js )

<!-- end snippet -->

Like this ( because you are not concatenating here, you are just printing those values )

答案2

得分: 1

response.json 返回解析后的 Json 作为一个 "Object"。您正在将此对象与一个字符串连接起来:

console.log("json " + json);

因此,您将获得字符串表示形式。您可能想要:

console.log("json ", json);

英文:

response.json returns the parsed Json as an "Object". You are concatenating this object with a string:

console.log(&quot;json &quot; + json);

Hence you will get the String representation. You probably want:

console.log(&quot;json &quot;, json);

huangapple
  • 本文由 发表于 2023年5月17日 14:14:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76269035.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定