简体   繁体   English

将ReactJS与NodeJS一起使用

[英]Using ReactJS with NodeJS

I have an application which need to interact with UI and perform various CURD operation to database in the backend, 我有一个需要与UI交互并在后端对数据库执行各种CURD操作的应用程序,

At present I we have a angular 1.2 application which have the UI and another node application and for every and the angular application sends http request to node application for every interaction needed, so here I have two different services. 目前,我们有一个angular 1.2应用程序,该应用程序具有UI和另一个节点应用程序,并且对于每个应用程序,Angular应用程序都会向节点应用程序发送http请求以进行所需的每次交互,因此这里有两个不同的服务。

I wanted to combine these operations into a one single service means UI(React) and node in one single service, like react inside node, when I start node server I should be able to access by UI also ,I am using express in node, what is the best way to do to use ReactJS with Node in a single service. 我想将这些操作组合到一个单一的服务中,即UI(React)和节点在一个单一的服务中,例如在节点内部进行反应,当我启动节点服务器时,我也应该能够通过UI进行访问,我在节点中使用了express,在单个服务中将ReactJS与Node一起使用的最佳方法是什么?

Hope you are using express along with nodejs. 希望您将Express与Node.js一起使用。 You could place the react application folder inside your node application folder in some folder named client. 您可以将react application文件夹放在节点应用程序文件夹中某个名为client的文件夹中。 Then from node app you could do the following to server react files: 然后,从节点应用程序中,您可以执行以下操作来处理文件:

var app = express();
app.use(express.static(path.join(__dirname, 'client')));

After all the application specific routes to serve your apis, provide the following to serve index.html for all other get requests. 在为您的api提供服务的所有特定于应用程序的路由之后,提供以下内容为所有其他get请求提供index.html服务。

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname+'/client/index.html'));
});

In order to execute http requests from a react application ( it doesn't matter if you backend is node ), I recommend using fetch api : 为了执行来自react应用程序的http请求( 后端是否为node都没有关系 ),我建议使用fetch api

fetch(url)
  .then(response => response.json())
  .then(response => /* Do what you need with it */)

Axios also works quite good and provides the same result: Axios也可以很好地工作并提供相同的结果:

axios.get(url)
  .then(response => response => /* Do what you need with it */)
  .catch(error => console.log(error))

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

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