在从REST API到我的前端获取数据时遇到了错误。

huangapple go评论61阅读模式
英文:

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 -&gt; I've to fetch data here and console.log it

import { useEffect, useState } from &quot;react&quot;;
import Header from &quot;../../components/header/Header&quot;;
import Posts from &quot;../../components/posts/Posts&quot;;
import Sidebar from &quot;../../components/sidebar/Sidebar&quot;;
import &quot;./home.css&quot;;
import axios from &quot;axios&quot;;

const Home = () =&gt; {
  const [posts, setposts] = useState([]);

  const fetchPosts = async () =&gt; {
    try {
      const res = await axios.get(&quot;http://localhost:5000/api/posts&quot;);
      console.log(res.data);
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() =&gt; {
    fetchPosts();
  }, []);

  return (
    &lt;&gt;
      &lt;Header /&gt;
      &lt;div className=&quot;home&quot;&gt;
        &lt;Posts /&gt;
        &lt;Sidebar /&gt;
      &lt;/div&gt;
    &lt;/&gt;
  );
};

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(&quot;dotenv&quot;);
const express = require(&quot;express&quot;);
const app = express();
const mongoose = require(&quot;mongoose&quot;);
const authRoute = require(&quot;./routes/auth&quot;);
const userRoute = require(&quot;./routes/users&quot;);
const postRoute = require(&quot;./routes/posts&quot;);
const categoryRoute = require(&quot;./routes/categories&quot;);

dotenv.config();
app.use(express.json());

const cors = require(&quot;cors&quot;);
app.use(cors());

mongoose
  .connect(process.env.MONGO_URL)
  .then(() =&gt; {
    console.log(&quot;Connect to database&quot;);
  })
  .catch((err) =&gt; {
    console.log(err);
  });


app.use(&quot;/api/auth&quot;, authRoute);
app.use(&quot;/api/users&quot;, userRoute);
app.use(&quot;/api/posts&quot;, postRoute);
app.use(&quot;/api/categories&quot;, categoryRoute);

app.listen(process.env.PORT, () =&gt; {
  console.log(&quot;Server is running on port: &quot; + process.env.PORT);
});

答案1

得分: 3

我看到你的React前端正在端口3000上运行,而你的API正在端口5000上运行。因此,由于这种差异,你的浏览器将API的请求视为跨源请求,并根据其CORS策略进行了阻止。

在开发应用程序时,你可以关闭浏览器的安全性,以便它不会阻止跨源请求。

当构建应用程序时,你可以通过从API中提供前端来避免跨源请求,这样只有一个服务器提供前端和API的数据。要做到这一点,你需要构建前端并将文件作为静态文件从服务器提供,然后将任何带有/api前缀的URL路由到你的API,并从顶级路由(/)提供你的应用程序。

在Express.js中,代码看起来类似以下内容:

import routes from &quot;./routes&quot;

const frontendPath = path.resolve(__dirname, &quot;..&quot;, &quot;..&quot;, &quot;frontend&quot;, &quot;dist&quot;);

// 路由
// 捕捉任何带有/api前缀的路由
app.use(&quot;/api&quot;, routes)
// 未解析的api路由
app.use(/\/api\/.*/, (req: Request, res: Response) =&gt; {
    res.status(404).json({ status: &quot;error&quot;, message: `Could not find ${req.originalUrl}` });
})

// 前端
// 将不包含/api的所有路由传递给前端
app.use(express.static(frontendPath))
app.use((_, res) =&gt; {
    res.sendFile(path.join(frontendPath, &quot;index.html&quot;))
})

其中,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 &quot;./routes&quot;

const frontendPath = path.resolve(__dirname, &quot;..&quot;, &quot;..&quot;, &quot;frontend&quot;, &quot;dist&quot;);

// Routes
// catch any routes with prefix /api
app.use(&quot;/api&quot;, routes)
// api route that does not resolve
app.use(/\/api\/.*/, (req: Request, res: Response) =&gt; {
    res.status(404).json({ status: &quot;error&quot;, 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) =&gt; {
    res.sendFile(path.join(frontendPath, &quot;index.html&quot;))
})

Where routes is a collection of routes defined in another file.

huangapple
  • 本文由 发表于 2023年4月13日 20:52:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76005662.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定