无法使用 fetch api ReactJS/nodeJS 显示我的消息

问题描述 投票:0回答:1

我想使用 fetch API 调用。 为了尝试它是否有效,我尝试显示一条消息。

在我的 NodeJs 服务器中,我:

app.get('/api', (req, res) => {
res.send({
    message: 'Hi'
})

})

在我的前端文件夹中,在我的 app.js 中:

 import React, {useState} from 'react';

  const App = () => {

  const [message, setMsg] = useState('');
  
  const handleClick = async () => {
    console.log('click');

    fetch('/api')
      .then((response) => {
        return response.json();
      })
      .catch((error) => {
        console.error(`${error}`)
      })
      .then(json => console.log(json))
      .catch((error) => {
        console.error(`Couldn't convert the json: ${error}`)
      });
    setMsg(message);
  };
  
  return (
    <div className="App">
        <button onClick={handleClick}>
          Button
        </button>
        <p>{message}</p>
    </div>
  );
}

export default App;

一切正常,当我在浏览器中加载应用程序时,检查器中没有错误, 当我点击我的按钮时: 我的控制台显示:

点击

我的 json 显示:

{消息:'嗨'} >消息:“嗨” >[[原型]]:对象

但我的消息不适用于

<p>{message}<p>

当我将“测试”放入

setMsg(console.log('test'))
时,它就起作用了。 当我把它放进去时
<p>test</p>
它就起作用了

我真的不明白我的

<p>{message}</p>
不显示..

感谢您的帮助

reactjs node.js fetch-api display
1个回答
1
投票

这应该适合你:

const handleClick = async () => {
    console.log('click');
    fetch('/api')
      .then((response) => {
        return response.json();
      })
      .catch((error) => {
        console.error(`${error}`)
      })
      .then(json => {
        setMsg(json.message)
      })
      .catch((error) => {
        console.error(`Couldn't convert the json: ${error}`)
      });
};
© www.soinside.com 2019 - 2024. All rights reserved.