这是我在 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"
}
这是我在记录来自 fetch 的响应而不转换为 JSON 时得到的响应。
https://photos.google.com/photo/AF1QipMZXrNK-8MdosXzUXlqQvpwtlYhe6xCmmJ70xIc https://i.stack.imgur.com/ud1u9.png