【发布时间】:2022-09-30 02:18:55
【问题描述】:
这是我在 Node 中的后端代码
import express from \'express\';
import fetch from \'node-fetch\';
const PORT = process.env.PORT || 3001;
const app = express();
app.get(\"/getData\", (req, res) => {
let url = \"https://jsonplaceholder.typicode.com/users\";
fetch(url)
.then(result => result.json())
.then(json => {
res = res.json(json);
})
});
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});
独立运行它会给我想要的输出 - 这是一个对象数组列表
现在,这是我在 react 中的前端代码。
import React from \"react\";
import logo from \"./logo.svg\";
import \"./App.css\";
function App() {
const [data, setData] = React.useState(null);
React.useEffect(() => {
fetch(\"/getData\")
.then((res) => res.json())
.then((data) => setData(data.message));
}, []);
return (
<div className=\"App\">
<header className=\"App-header\">
<img src={logo} className=\"App-logo\" alt=\"logo\" />
<p>{!data ? \"Loading...\" : data}</p>
</header>
</div>
);
}
export default App;
运行它会在检查期间在控制台中给我上面提到的异常,并且没有 UI 输出。
这是我的 package.json 文件
{
\"name\": \"node-react-project\",
\"version\": \"1.0.0\",
\"description\": \"\",
\"main\": \"index.js\",
\"scripts\": {
\"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",
\"start\": \"node server/index.js\"
},
\"keywords\": [],
\"author\": \"\",
\"license\": \"ISC\",
\"dependencies\": {
\"express\": \"^4.18.1\",
\"node-fetch\": \"^3.2.10\"
},
\"proxy\": \"http://localhost:3001\",
\"type\": \"module\"
}
这是我在不转换为 JSON 的情况下记录来自 fetch 的响应时得到的响应。
https://photos.google.com/photo/AF1QipMZXrNK-8MdosXzUXlqQvpwtlYhe6xCmmJ70xIc
-
首先,我认为在进行 fetch 响应时,您必须放置完整的 url 而不仅仅是端点
-
在第二个之后放一个 .catch 然后我想你可以看到完整的错误
-
@HarshGupta 我尝试输入完整的网址,但遇到了类似的问题。如果完整的网址是指“localhost:3000/getData\”而不是文件位置。
-
@HarshGupta,我认为我将错误理解为 res.json() 正在尝试将 HTML 页面解析为 JSON 格式,但是我如何从 api 获取 HTML 页面作为响应,其中我清楚地返回 JSON 响应是超越我。
-
然后删除所有 json 转换,然后记录响应,看看你到底得到了什么