这是快速后端和 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 在 locahost:9000 上工作
proxy:http://localhost:9000 在前端react应用程序的 package.json 中添加
请告诉我是怎么回事,我该如何解决。谢谢