如何在同一端口上运行 Json 服务器和 ReactJS

发布于 2025-01-20 05:00:21 字数 108 浏览 4 评论 0原文

我正在尝试使用 JSON 服务器作为我的后端 API 来运行 React 应用程序。 但是在不同端口上运行时出现 CORS 错误

我需要一些解决方案,以便我可以在同一端口上运行 提前致谢!

I am trying to run React application using JSON server- as my backend API.
But getting CORS error while running on different port

I need some solution so that i can run on same port
Thanks in Advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

稍尽春風 2025-01-27 05:00:21

您不能两次打开同一端口。

You have basically two options

  1. Setup a proxy
  2. Implement CORS headers

Proxy

You can integrate proxy directly using nodejs - CRA supports this option:

Conveniently, this avoids CORS issues and error messages like this in development:

Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

实施CORS CORS

ILLACH CORS ILLACHEN CORS HEARBER并不那么困难看起来像。

请参阅JSON服务器的文档: https://www.npmjs.coms.coms.coms.coms.coms.com/package/json/json -Server

const jsonServer = require('json-server')
const server = jsonServer.create()
const middlewares = jsonServer.defaults()

// Set default middlewares (logger, static, cors and no-cache)
server.use(middlewares)

如果您直接通过命令行使用JSON服务器,也有一个CLI选项。默认情况下,启用了CORS。因此,似乎您需要jsonserver.defaults()来创建中间件。

You can't open the same port twice.

You have basically two options

  1. Setup a proxy
  2. Implement CORS headers

Proxy

You can integrate proxy directly using nodejs - CRA supports this option: https://create-react-app.dev/docs/proxying-api-requests-in-development/

Conveniently, this avoids CORS issues and error messages like this in development:

Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Implement CORS

Implement CORS headers is not as hard as it might look like.

Please see the documentation of the json server: https://www.npmjs.com/package/json-server

const jsonServer = require('json-server')
const server = jsonServer.create()
const middlewares = jsonServer.defaults()

// Set default middlewares (logger, static, cors and no-cache)
server.use(middlewares)

There is also a CLI option if you use json-server directly via command line. By default, CORS are enabled. Therefore it seems that you need the jsonServer.defaults() to create your middlewares.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文