这是来自 Express 后端和 MongoDB 数据库的路由代码以及来自前端的正常调用fetch("/")
它返回index.html代码并添加fetch("http://localhost:9000")
它返回 CORS 错误,所以我添加了app.use(cors())
.
router.get("/", async (req, res) => {
Journal.find({}, function (err, journals) {
if (err) {
res.send("Something went wrong");
}
res.json(journals);
});
});
这是从reactjs前端发出的axios和fetch请求,在“/”上进行fetch和axios调用时,后端没有任何结果,只有index.html代码被返回,因此我开始使用“http://localhost: 9000”然后数据即将到来,但出现了本地主机问题。
const [journals, setJournals] = useState([
{ title: "Day 1", content: content_string },
]);
useEffect(() => {
getJournalData();
});
// const getJournalData = async () => {
// try {
// const res = await fetch("http://localhost:9000/");
// const data = await res.json();
// setJournals(data);
// console.log(data);
// } catch (err) {
// console.error(err);
// }
// };
const getJournalData = () => {
axios
.get("http://localhost:9000/")
.then((res) => {
setJournals(res.data);
})
.catch((err) => console.error(err));
};
这是 chrome-dev-tools 网络选项卡:
控制台内容
React 正在 localhost:3000 上运行
Express 正在 localhost:9000 上运行
proxy:http://localhost:9000 添加到前端 React 应用程序的 package.json 中
请告诉我发生了什么事以及如何解决它。
谢谢