heroku服务器_如何在Heroku上使用Express服务器部署React应用

heroku服务器

by Ashish Nandan Singh

通过Ashish Nandan Singh

如何在Heroku上使用Express服务器部署React应用 (How to deploy a React app with an Express server on Heroku)

Hello, world! Recently I had to deploy a website to Heroku for one of the pieces of freelance work I was doing. I think this process may be somewhat difficult, and a detailed tutorial or article on how to do this should help. So this one is going to be very simple and hopefully very short.

你好,世界! 最近,我不得不为Heroku部署一个网站,这是我正在做的一项自由职业。 我认为此过程可能有些困难,有关如何执行此操作的详细教程或文章应该会有所帮助。 因此,这将非常简单,希望非常短。

We will start by creating an Express app, which will act as our server. Once the server is done, we will create a simple create-react-app application, connect the server with the frontend and, finally, deploy the whole thing to a hosting platform such as Heroku.

我们将从创建一个Express应用开始,它将作为我们的服务器。 服务器完成后,我们将创建一个简单的create-react-app应用程序,将服务器与前端连接,最后将整个内容部署到托管平台(例如Heroku)。

Before we go any further, I want you to understand that in the world of web development almost everything is up to one’s preference. Some of you may disagree on certain things, you may continue the way you want to do things, and that’s totally fine. Up to the point when we’re breaking the application I consider everything to be fine.

在继续之前,我希望您了解在Web开发领域中,几乎所有事情都取决于您的喜好。 你们中的某些人可能在某些事情上存在分歧,可以继续做自己想做的事情,那完全没问题。 直到我们破坏应用程序为止,我认为一切都很好。

Let’s get started.

让我们开始吧。

创建一个Node / Express应用 (Create a Node/Express app)

Start by creating a folder for the overall project. This folder will contain the client side application — our React app in this case. Navigate to the directory in your terminal and type the commands below.

首先为整个项目创建一个文件夹。 该文件夹将包含客户端应用程序-在这种情况下为我们的React应用程序。 导航到终端中的目录,然后输入以下命令。

$ touch server.js$ npm init

The last command from the above snippet will take you through some of the steps and will initialise your project with a package.json file. If you are totally new to this, you can consider this file to be a ledger where you keep the record of all the dependencies you’ll be using across the build process of your application.

以上代码段中的最后一条命令将带您完成一些步骤,并使用package.json文件初始化您的项目。 如果您对此还不陌生,则可以将此文件视为分类帐,在其中记录您将在应用程序的构建过程中使用的所有依赖项的记录。

Moving on, now that we have the package.json file ready, we can start by adding our dependency for the project.

继续,现在我们已经准备好package.json文件,我们可以从添加项目依赖关系开始。

Adding Express:

添加Express:

$ npm i -g express --save

This will add Express as a dependency to your package.json. Now that we have this, all we need is one more dependency and that is for hot reloading of the app whenever we make some change to the code:

这会将Express添加为package.json的依赖项。 现在我们有了这个,我们所需要的就是一个依赖关系,那就是每当我们对代码进行一些更改时就可以热加载应用程序:

$ npm i -g nodemon --save --dev

This will add nodemon to the app. If you would like to read more about nodemon, you can check this link for more information.

这会将nodemon添加到应用程序。 如果您想了解有关nodemon的更多信息,可以查看链接以获取更多信息。

Now that we have these added, we are all set to create our most basic server in Express. Let’s see how that’s done.

现在我们已经添加了这些,我们都可以在Express中创建最基本的服务器。 让我们看看如何完成。

const express = require('express');const app = express();const port = process.env.PORT || 5000;
//Route setupapp.get('/', (req, res) => {    res.send('root route');
})
//Start serverapp.listen(port, (req, res) => {
console.log(`server listening on port: ${port}`)
});

That’s it. Just navigate to the terminal, make sure you are in the root directory of the project, and type:

而已。 只需导航到终端,确保您在项目的根目录中,然后键入:

$ nodemon <name-of-the-file> (index.js/server.js)

In our case since we named it server.js it would be nodemon server.js . This will start the server on port 5000 of your computer locally. If you go visit the browser and open https://localhost:5000/ you will see the text “root route”, which means the server has started. In case you face any issues, feel free to add them in the comments below.

在我们的例子中,由于我们将其命名为server.js因此它将是nodemon server.js 这将在本地计算机的端口5000上启动服务器。 如果您访问浏览器并打开https:// localhost:5000 / ,将看到文本“ root route”,这表示服务器已启动。 如果您遇到任何问题,请随时在下面的评论中添加它们。

Now that the server is set up and is working, let’s proceed towards getting the React app setup.

现在服务器已经设置好并且可以正常工作了,让我们继续进行React应用的设置。

React应用 (React app)

$ npm i -g create-react-app$ create-react-app <name-of-the-app>

For the purpose of this tutorial we will name the app “client,” so our command will look like this create-react-app client.

在本教程中,我们将应用程序命名为“ client”,因此我们的命令将类似于此create-react-app client

Once this is done, the setup will take some time and will create a nice little folder inside your main application with the name “client”.

一旦完成,设置将花费一些时间,并将在主应用程序中创建一个名为“ client”的漂亮小文件夹。

We will not make any major changes in the overall React application for now — that is outside the scope of this tutorial.

目前,我们不会在整个React应用程序中进行任何重大更改-这不在本教程的范围内。

Now the challenge is that we need to call and connect with our server running on the localhost. To do that we need to make an API call.

现在的挑战是,我们需要调用并连接在本地主机上运行的服务器。 为此,我们需要进行API调用。

添加代理 (Adding a proxy)

React gives us the ability to do so by adding a proxy value to our package.json file. Navigate to the package.json file in your directory and add the piece of code below.

通过向我们的package.json文件添加代理值,React使我们能够做到这一点。 导航到目录中的package.json文件,然后在下面添加代码。

"proxy": "http://localhost:5000",

In our case, the server is running at port 5000, hence the 5000 in the proxy value. The value may vary if you are using a different port altogether.

在我们的例子中,服务器在端口5000上运行,因此代理值是5000。 如果您完全使用其他端口,则该值可能会有所不同。

Now we need to call the Express-defined endpoints, or API endpoints, from our React components. What that really means is that now we can simply call “api/users/all” from our client side, which will then proxy our request and it will look like this “https://localhost:5000/api/users/all". This saves us from making a cross origin request, which most of the modern browsers do not allow for security reasons.

现在,我们需要从我们的React组件中调用Express定义的端点或API端点。 真正的意思是,现在我们可以从客户端简单地调用“ api / users / all”,然后它将代理我们的请求,并且看起来像“ https:// localhost:5000 / api / users / all”这使我们免于发出跨源请求,出于安全原因,大多数现代浏览器不允许这样做。

Next we will make some changes to the src/app.js file.

接下来,我们将对src/app.js文件进行一些更改。

import React, { Component } from 'react';import './App.css';import Navbar from './Components/Layout/Navbar';import { BrowserRouter as Router, Route } from 'react-router-dom';import Footer from './Components/Layout/Footer';import Home from './Components/Layout/Home';import Social from './Components/social/Social';
class App extends Component {  constructor(props) {    super(props);    this.state = {}    this.connecToServer = this.connecToServer.bind(this);  }
connecToServer() {    fetch('/');  }
componentDidMount() {    this.connecToServer();  }
render() {    return (      <Router>      <div className="container">         <Navbar />         <Route exact path="/" component={Home} />         <Route exact path="/social" component={Social} />         <Footer />      </div>      </Router>    );  }}
export default App;

What we did was to create a constructor, and bind the value of this in our function which will make the fetch API call. Then we call the function as soon as the component is mounted. Next we have the render function which has the overall markup for the app. So that was the last change we will do in React or our frontend application.

我们要做的是创建一个构造函数,并将其值绑定到我们的函数中,这将进行fetch API调用。 然后,我们在安装组件后立即调用该函数。 接下来,我们有render函数,它具有应用程序的整体标记。 这就是我们将在React或前端应用程序中做的最后更改。

Your package.json file should look like the code snippet below.

您的package.json文件应类似于以下代码片段。

{  "name": "project-name",  "version": "0.1.0",  "private": true,  "dependencies": {    "react": "^16.6.3",    "react-dom": "^16.6.3",    "react-scripts": "2.1.1",    "react-router-dom": "^4.3.1"  },
"scripts": {    "start": "react-scripts start",    "build": "react-scripts build",    "test": "react-scripts test",    "eject": "react-scripts eject"  },
"eslintConfig": {    "extends": "react-app"  },
"proxy": "http://localhost:5000",
"browserslist": [    ">0.2%",    "not dead",    "not ie <= 11",    "not op_mini all"  ]}

Now let’s pause for a minute and think about what we need to do next…. any thoughts?

现在让我们暂停片刻,然后考虑下一步需要做什么……。 有什么想法吗?

Some of you are right by thinking we need to make sure our React files are being served by our Express server. Let’s make some modifications to the server.js file to make sure that the React files get served by the Express server.

某些人认为我们需要确保由Express服务器提供React文件是对的。 让我们对server.js文件进行一些修改,以确保Express服务器可以提供React文件。

服务器文件更改 (Server file change)
const express = require('express');const app = express();const path = require('path');const port = process.env.PORT || 5000;
//Static file declarationapp.use(express.static(path.join(__dirname, 'client/build')));
//production modeif(process.env.NODE_ENV === 'production') {  app.use(express.static(path.join(__dirname, 'client/build')));  //  app.get('*', (req, res) => {    res.sendfile(path.join(__dirname = 'client/build/index.html'));  })}
//build modeapp.get('*', (req, res) => {  res.sendFile(path.join(__dirname+'/client/public/index.html'));})
//start serverapp.listen(port, (req, res) => {  console.log( `server listening on port: ${port}`);})

In the above code snippet, first you need to use the inbuilt path module in node and declare the static folder you would like to use in this Express server.

在上面的代码片段中,首先需要在node中使用内置的路径模块,并声明要在此Express服务器中使用的静态文件夹。

Then you check if the process is production, which it will be once the app is deployed to Heroku. Under this condition you would like to serve the index.html file from the build folder and not the public folder.

然后,您检查该过程是否是生产过程,一旦将应用程序部署到Heroku,就将开始生产 。 在这种情况下,您希望从构建文件夹而不是公用文件夹中提供index.html文件。

If it’s not the production mode, and you are testing some feature and your server is running on the localhost, you would like the index.html from the public folder to be served.

如果不是生产模式,并且您正在测试某些功能,并且您的服务器正在本地主机上运行,​​则希望提供公共文件夹中的index.html

Now we need to make sure that first we start our Express server and then go about starting our React server. Now there are a lot of ways to do this, and for the simplicity of this tutorial we will be using a module called concurrently to run both the servers with one command.

现在我们需要确保首先启动Express服务器,然后再启动React服务器。 现在有很多方法可以做到这一点,为了简化本教程,我们将使用concurrently调用的模块。 使用一个命令运行两个服务器。

Make sure you are in the root directory, and then run the command below from your terminal.

确保您位于根目录中,然后从终端运行以下命令。

npm i concurrently --save

After doing this, let’s make some changes to the scripts we have in our Express server package.json files.

完成此操作后,让我们对Express服务器package.json文件中的脚本进行一些更改。

"scripts": {    "client-install": "npm install --prefix client",    "start": "node index.js",    "server": "nodemon index.js",    "client": "npm start --prefix client",    "dev": "concurrently \"npm run server\" \"npm run client\"",
}
  • npm run client-install will install all the dependencies for the React application

    npm run client-install将安装React应用程序的所有依赖项

  • npm start will start the server and not reload after detecting any change

    npm start将启动服务器,并且在检测到任何更改后不会重新加载

  • npm run server will start the server, listen for any changes in the code, and hot reload the page on browser to reflect the change.

    npm run server将启动服务器,侦听代码中的任何更改,然后在浏览器中重新加载页面以反映更改。

  • npm run client will run the React application without starting the server

    npm run client将在不启动服务器的情况下运行React应用程序

  • npm run dev will concurrently run the server and then run the client on your browser

    npm run dev将同时运行服务器,然后在浏览器上运行客户端

Heroku设置 (Heroku setup)

Make sure you have an account on Heroku. If you don’t, you can make one using your GitHub credentials very quickly.

确保您在Heroku上拥有一个帐户。 如果不这样做,则可以非常快速地使用GitHub凭据创建一个。

Next we will install the Heroku CLI , which will help us deploy the application right from our terminal. Click here to get install instructions on both macOS and Windows.

接下来,我们将安装Heroku CLI,这将帮助我们从终端直接部署应用程序。 单击此处以获取在macOS和Windows上的安装说明。

$ heroku login

Enter the login credentials for Herkou and then:

输入Herkou的登录凭据,然后:

$ heroku create

This will create an application for you. If you visit the Heroku dashboard now, it will have the application there.

这将为您创建一个应用程序。 如果您现在访问Heroku仪表板,它将在其中具有应用程序。

Now we need to make sure we have a build folder in our project before we push the project to the Heroku repository. Add the script below into your package.json file.

现在,在将项目推送到Heroku存储库之前,我们需要确保在项目中有一个build文件夹。 将以下脚本添加到package.json文件中。

"scripts": {    "client-install": "npm install --prefix client",
"start": "node server.js",
"server": "nodemon server.js",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"heroku-postbuild":      "NPM_CONFIG_PRODUCTION=false npm install --prefix client        && npm run build --prefix client"  },

After doing this, save the file and push the entire project repository to your Heroku application branch.

完成此操作后,保存文件并将整个项目存储库推送到您的Heroku应用程序分支。

//add remote
$ heroku git:remote -a application-name
$ git add .
$ git commit -am 'prepare to deploy'
$ git push heroku master

And that should be it.

就是这样。

Once this is all done, you will get a URL for your live hosted project. Share and showcase what you can build using these technologies.

完成所有操作后,您将获得实时托管项目的URL。 分享并展示您可以使用这些技术构建的内容。

If you have any questions or comments feel free to add your comment or connect directly.

如果您有任何疑问或评论,请随时添加您的评论或直接连接。

Github: https://github.com/ashishcodes4

GitHub: https : //github.com/ashishcodes4

Twitter: https://twitter.com/ashishnandansin

推特: https : //twitter.com/ashishnandansin

LinkedIn: https://www.linkedin.com/in/ashish-nandan-singh-490987130/

领英(LinkedIn): https : //www.linkedin.com/in/ashish-nandan-singh-490987130/

翻译自: https://www.freecodecamp.org/news/how-to-deploy-a-react-app-with-an-express-server-on-heroku-32244fe5a250/

heroku服务器

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值