英文:
Facing errors in fetching data from rest API to my front-end
问题
I am trying to fetch data from my rest api to my react front-end and i'm getting some errors like
This image contains all the errors i'm facing
My server is running on "http://localhost:5000"
Home.jsx -> I've to fetch data here and console.log it
import { useEffect, useState } from "react";
import Header from "../../components/header/Header";
import Posts from "../../components/posts/Posts";
import Sidebar from "../../components/sidebar/Sidebar";
import "./home.css";
import axios from "axios";
const Home = () => {
const [posts, setposts] = useState([]);
const fetchPosts = async () => {
try {
const res = await axios.get("http://localhost:5000/api/posts");
console.log(res.data);
} catch (err) {
console.log(err);
}
};
useEffect(() => {
fetchPosts();
}, []);
return (
<>
<Header />
<div className="home">
<Posts />
<Sidebar />
</div>
</>
);
};
export default Home;
I've checked my server is running and the url is also correct as it is giving back data when i'm requesting data from it in postman.
Server.js -> CORS is added in my server code
const dotenv = require("dotenv");
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const authRoute = require("./routes/auth");
const userRoute = require("./routes/users");
const postRoute = require("./routes/posts");
const categoryRoute = require("./routes/categories");
dotenv.config();
app.use(express.json());
const cors = require("cors");
app.use(cors());
mongoose
.connect(process.env.MONGO_URL)
.then(() => {
console.log("Connect to database");
})
.catch((err) => {
console.log(err);
});
app.use("/api/auth", authRoute);
app.use("/api/users", userRoute);
app.use("/api/posts", postRoute);
app.use("/api/categories", categoryRoute);
app.listen(process.env.PORT, () => {
console.log("Server is running on port: " + process.env.PORT);
});
(Note: This is a translation of the code you provided. If you have any specific questions or need further assistance, please let me know.)
英文:
I am trying to fetch data from my rest api to my react front-end and i'm getting some errors like
This image contains all the errors i'm facing
My server is running on "http://localhost:5000"
Home.jsx -> I've to fetch data here and console.log it
import { useEffect, useState } from "react";
import Header from "../../components/header/Header";
import Posts from "../../components/posts/Posts";
import Sidebar from "../../components/sidebar/Sidebar";
import "./home.css";
import axios from "axios";
const Home = () => {
const [posts, setposts] = useState([]);
const fetchPosts = async () => {
try {
const res = await axios.get("http://localhost:5000/api/posts");
console.log(res.data);
} catch (err) {
console.log(err);
}
};
useEffect(() => {
fetchPosts();
}, []);
return (
<>
<Header />
<div className="home">
<Posts />
<Sidebar />
</div>
</>
);
};
export default Home;
I've checked my server is running and the url is also correct as it is giving back data when i'm requesting data from it in postman.
Server.js -> CORS is added in my server code
const dotenv = require("dotenv");
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const authRoute = require("./routes/auth");
const userRoute = require("./routes/users");
const postRoute = require("./routes/posts");
const categoryRoute = require("./routes/categories");
dotenv.config();
app.use(express.json());
const cors = require("cors");
app.use(cors());
mongoose
.connect(process.env.MONGO_URL)
.then(() => {
console.log("Connect to database");
})
.catch((err) => {
console.log(err);
});
app.use("/api/auth", authRoute);
app.use("/api/users", userRoute);
app.use("/api/posts", postRoute);
app.use("/api/categories", categoryRoute);
app.listen(process.env.PORT, () => {
console.log("Server is running on port: " + process.env.PORT);
});
答案1
得分: 3
我看到你的React前端正在端口3000
上运行,而你的API正在端口5000
上运行。因此,由于这种差异,你的浏览器将API的请求视为跨源请求,并根据其CORS策略进行了阻止。
在开发应用程序时,你可以关闭浏览器的安全性,以便它不会阻止跨源请求。
当构建应用程序时,你可以通过从API中提供前端来避免跨源请求,这样只有一个服务器提供前端和API的数据。要做到这一点,你需要构建前端并将文件作为静态文件从服务器提供,然后将任何带有/api
前缀的URL路由到你的API,并从顶级路由(/
)提供你的应用程序。
在Express.js中,代码看起来类似以下内容:
import routes from "./routes"
const frontendPath = path.resolve(__dirname, "..", "..", "frontend", "dist");
// 路由
// 捕捉任何带有/api前缀的路由
app.use("/api", routes)
// 未解析的api路由
app.use(/\/api\/.*/, (req: Request, res: Response) => {
res.status(404).json({ status: "error", message: `Could not find ${req.originalUrl}` });
})
// 前端
// 将不包含/api的所有路由传递给前端
app.use(express.static(frontendPath))
app.use((_, res) => {
res.sendFile(path.join(frontendPath, "index.html"))
})
其中,routes
是在另一个文件中定义的路由集合。
英文:
I see that your React frontend is running on port 3000
and your API is running on port 5000
. Because of this difference, your browser sees the request to the API as a cross origin request and has blocked it according to its CORS Policy.
While developing the application, you could turn off your browser's secutiy so it will not block cross origin requests.
When you build your app, you can avoid cross origin requests by serving your frontend from your API, so that only one server is serving your frontend and data from your API. To do this, you need to build the frontend and serve the files as static files from your server, then route any URL with /api
to your API, and serve your app from the top level route (/
).
In Express.js, it looks something like the following:
import routes from "./routes"
const frontendPath = path.resolve(__dirname, "..", "..", "frontend", "dist");
// Routes
// catch any routes with prefix /api
app.use("/api", routes)
// api route that does not resolve
app.use(/\/api\/.*/, (req: Request, res: Response) => {
res.status(404).json({ status: "error", message: `Could not find ${req.originalUrl}` });
})
// Frontend
// pass all routes that do not contain /api to the frontend
app.use(express.static(frontendPath))
app.use((_, res) => {
res.sendFile(path.join(frontendPath, "index.html"))
})
Where routes
is a collection of routes defined in another file.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论