将 React js 应用程序与节点 js 服务器连接的最佳方法是什么?

What is the best way to connect React js app with node js server?

我已经构建并测试了我的 ReactJS 应用程序和 NodeJS 服务器。 React 应用程序有一个登录表单,我想将其数据发送到服务器并从那里获取网络令牌。 我正在使用 Axios 通过以下代码发送它:

  const sendData = (e) => {
    e.preventDefault();
    axios
      .post(url, data)
      .then((res) => console.log("Data send" + data))
      .catch((err) => console.log(err));
  }; 

但我在 Brave Browser 中遇到了这个错误

Access to XMLHttpRequest at 'http://localhost:3000/api/v1/users/signup' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

请告诉我这是最佳做法吗?如果是,如何摆脱这个错误,如果不是,更好的方法是什么?

我希望这个 geeksforgeeks 的详细解释 link 对您有帮助 - -

https://www.geeksforgeeks.org/how-to-connect-node-js-with-react-js/

由于您的前端位于一个 URL(例如 localhost:3000)并且您的后端服务器位于在另一个 URL 上(例如 localhost:5000)。出于安全目的,浏览器具有此功能,作为仅允许执行来自同一 URL 的请求的一种方式。

这种错误的解决方案在于服务器,以及控制它的方法,您需要使用this

进行配置

在expressjs中,您可以使用如下包:

const express = require('express')
const app = express()
const cors = require('cors')
 
app.use(cors())

如果你想要一个特定的 url 访问你的后端,你也可以将参数传递给 cors 中间件,否则如果你留空它意味着任何 URL 都有权利。

app.use(cors({
 origin: "http://yoururl"
}))

您可以查看文档了解更多详情。