简体   繁体   English

在 React.js 中使用 Express.js 的推荐方法?

[英]Recommended way for using Express.js with React.js?

I have found two ways to combine React and Express:我找到了两种结合 React 和 Express 的方法:

[OPTION 1] ExpressJS serve React static files [选项 1] ExpressJS 提供 React 静态文件

Fundamentally, the idea here is to have pre-compiled JavaScript files at your disposal before spinning up the server.从根本上说,这里的想法是在启动服务器之前让您可以使用预编译的 JavaScript 文件。 And then in Express middleware:然后在 Express 中间件中:

app.use(express.static(path.join(__dirname, '../client/build')));

And then in tandem have other endpoints that execute logic on server-side.然后与其他端点一起在服务器端执行逻辑。

[OPTION 2] Host React files separately [选项 2] 单独托管 React 文件

Basically, decouple the logic in entirety of Frontend and Backend with one server just for serving static JS files.基本上,将整个 Frontend 和 Backend 的逻辑与一台服务器分离,仅用于提供静态 JS 文件。 And then another Express server for running any queries against the database.然后是另一个 Express 服务器,用于对数据库运行任何查询。 And returning simple JSON responses.并返回简单的 JSON 响应。

Which one is the recommended way?哪一种是推荐的方式? Is there an advantage of using one approach over the other?使用一种方法比另一种方法有优势吗?

This is an opinionated question, and so I can only give an opinionated response.这是一个自以为是的问题,所以我只能给出一个自以为是的回答。

I personally recommend OPTION 1 because you'll run into Cross-Origin-Resource-Sharing (CORS) issues in a number of places when you decouple your front and back ends.我个人推荐选项 1,因为当您分离前端和后端时,您会在许多地方遇到跨源资源共享 (CORS) 问题。 This isn't to say that it can't be done, but it will be an annoying thing you'll have to deal with.这并不是说它不能完成,但这将是您必须处理的烦人的事情。

With option 2 you'll also most likely have to be sending any requests to your back end with absolute URL paths, which can be very tough to maintain when an application scales.使用选项 2,您很可能还必须使用绝对 URL 路径向后端发送任何请求,这在应用程序扩展时非常难以维护。

With option 1 you'll have more flexibility, less to maintain, and less annoying workarounds to implement.使用选项 1,您将拥有更大的灵活性、更少的维护和更少的烦人的变通方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM