heroku_如何使用Express.js和Heroku将应用程序部署到Web

heroku

If you are new to the world of web development, you will spend a lot of time learning how to build static sites with HTML, CSS and JavaScript.

如果您不熟悉Web开发,那么您将花费大量时间学习如何使用HTML,CSS和JavaScript构建静态网站。

You might then start learning how to use popular frameworks such as React, VueJS or Angular.

然后,您可能会开始学习如何使用流行的框架,例如ReactVueJSAngular

But after trying out a few new ideas and running some sites locally, you might wonder how to actually deploy your site or app. And as it turns out, it can sometimes be difficult to know where to start.

但是,在尝试了一些新想法并在本地运行了一些网站之后,您可能会想知道如何实际部署您的网站或应用程序。 事实证明,有时可能很难知道从哪里开始。

Personally, I find running an Express server hosted on Heroku one of the simplest ways to get going. This article will show you how to do this.

我个人认为,运行在Heroku上托管的Express服务器是最简单的方法之一。 本文将向您展示如何执行此操作。

Heroku is a cloud platform which supports a number of different programming languages and frameworks.

Heroku是一个云平台,支持多种不同的编程语言和框架。

This is not a sponsored post - there are of course many other solutions available, such as:

这不是赞助帖子-当然还有许多其他解决方案可用,例如:

Check them all out and see which suits your needs best.

全部检查一下,看看最适合您的需求。

Personally, I found Heroku the quickest and easiest to start using "out of the box". The free tier is somewhat limited in terms of resources. However, I can confidently recommend it for testing purposes.

就个人而言,我发现Heroku最快,最容易地开始使用“开箱即用”功能。 免费套餐在资源上有所限制。 但是,我可以放心推荐它用于测试目的。

This example will host a simple site using an Express server. Here are the high-level steps:

本示例将使用Express服务器托管一个简单站点。 以下是高级步骤:

  1. Setting up with Heroku, Git, npm

    使用Heroku,Git,npm进行设置
  2. Create an Express.js server

    创建一个Express.js服务器
  3. Create static files

    创建静态文件
  4. Deploy to Heroku

    部署到Heroku

It should take about 25 minutes in total (or longer if you want to spend more time on the static files).

总共大约需要25分钟(如果要在静态文件上花费更多的时间,则需要更长的时间)。

This article assumes you already know:

本文假定您已经知道:

  • Some HTML, CSS and JavaScript basics

    一些HTML,CSS和JavaScript基础
  • Basic command line usage

    基本命令行用法
  • Beginner-level Git for version control

    初学者级Git用于版本控制

You can find all the code in this repository.

您可以在此存储库中找到所有代码。

配置 (Setting up)

The first step in any project is to set up all the tools you know you'll need.

任何项目的第一步都是设置您需要的所有工具。

You'll need to have:

您需要具备以下条件:

1. Create a new directory and initialise a Git repository

1.创建一个新目录并初始化一个Git存储库

From the command line, create a new project directory and move into it.

在命令行中,创建一个新的项目目录并移至该目录。

$ mkdir lorem-ipsum-demo
$ cd lorem-ipsum-demo

Now you are in the project folder, initialise a new Git repository.

现在您在项目文件夹中,初始化一个新的Git存储库。

⚠️This step is important because Heroku relies on Git for deploying code from your local machine to its cloud servers ⚠️

step️这一步很重要,因为Heroku依赖Git将代码从本地计算机部署到其云服务器⚠️

$ git init

As a final step, you can create a README.md file to edit at a later stage.

最后一步,您可以创建一个README.md文件,以便稍后进行编辑。

$ echo "Edit me later" > README.md

2. Login to the Heroku CLI and create a new project

2.登录到Heroku CLI并创建一个新项目

You can login to Heroku using the Heroku CLI (command line interface). You will need to have a free Heroku account to do this.

您可以使用Heroku CLI(命令行界面)登录到Heroku。 您需要有一个免费的Heroku帐户才能执行此操作。

There are two options here. The default is for Heroku to let you login through the web browser. Adding the -i flag lets you login through the command line.

这里有两个选择。 Heroku的默认设置是允许您通过Web浏览器登录。 添加-i标志可让您通过命令行登录。

$ heroku login -i

Now, you can create a new Heroku project. I called mine lorem-ipsum-demo.

现在,您可以创建一个新的Heroku项目。 我叫我的lorem-ipsum-demo

$ heroku create lorem-ipsum-demo

Naming your project:

命名您的项目:

  • Heroku will generate a random name for your project if you don't specify one in the command.

    如果您未在命令中指定名称,Heroku将为您的项目生成一个随机名称。
  • The name will form part of the URL you can use to access your project, so choose one you like.

    该名称将构成您可用于访问项目的URL的一部分,因此请选择一个您喜欢的名称。
  • This also means that you need to choose a unique project name that no one else has used.

    这也意味着您需要选择一个其他人都没有使用过的唯一项目名称。
  • It is possible to rename your project later (so don't worry too much about getting the perfect name right now).

    以后可以重命名您的项目(因此不必担心现在就获得完美的名称)。

3. Initialise a new npm project and install Express.js

3.初始化一个新的npm项目并安装Express.js

Next, you can initialise a new npm project by creating a package.json file. Use the command below to do this.

接下来,您可以通过创建package.json文件来初始化一个新的npm项目。 使用以下命令执行此操作。

⚠️This step is crucial. Heroku relies on you providing a package.json file to know this is a Node.js project when it builds your app ⚠️

⚠️这一步至关重要。 Heroku依靠您提供package.json文件来在构建应用程序时知道这是一个Node.js项目⚠️

$ npm init -y

Next, install Express. Express is a widely used server framework for NodeJS.

接下来, 安装Express 。 Express是广泛用于NodeJS的服务器框架。

$ npm install express --save

Finally, you are ready to start coding!

最后,您准备开始编码!

编写一个简单的Express服务器 (Writing a simple Express server)

The next step is to create a file called app.js, which runs an Express server locally.

下一步是创建一个名为app.js的文件,该文件在本地运行Express服务器。

$ touch app.js

This file will be the entry point for the app when it is ready. That means, the one command needed to launch the app will be:

准备就绪后,此文件将成为应用程序的入口点。 这意味着,启动应用程序所需的一个命令将是:

$ node app.js

But first, you need to write some code in the file.

但是首先,您需要在文件中编写一些代码。

4. Edit the contents of app.js

4.编辑app.js的内容

Open app.js in your favourite editor. Write the code shown below and click save.

在您喜欢的编辑器中打开app.js 编写如下所示的代码,然后单击“保存”。

// create an express app
const express = require("express")
const app = express()

// use the express-static middleware
app.use(express.static("public"))

// define the first route
app.get("/", function (req, res) {
  res.send("<h1>Hello World!</h1>")
})

// start the server listening for requests
app.listen(process.env.PORT || 3000, 
	() => console.log("Server is running..."));

The comments should help indicate what is happening. But let's quickly break the code down to understand it further:

评论应有助于指示正在发生的事情。 但是让我们快速分解代码以进一步了解它:

  • The first two lines simply require the Express module and create an instance of an Express app.

    前两行仅需要Express模块​​并创建Express应用程序的实例。
  • The next line requires the use of the express.static middleware. This lets you serve static files (such as HTML, CSS and JavaScript) from the directory you specify. In this case, the files will be served from a folder called public.

    下一行需要使用express.static中间件。 这样,您就可以从指定的目录中提供静态文件(例如HTML,CSS和JavaScript)。 在这种情况下,文件将从名为public的文件夹中提供。

  • The next line uses app.get() to define a URL route. Any URL requests to the root URL will be responded to with a simple HTML message.

    下一行使用app.get()定义URL路由。 对根URL的任何URL请求都将通过一条简单HTML消息进行响应。

  • The final part starts the server. It either looks to see which port Heroku will use, or defaults to 3000 if you are running locally.

    最后一部分启动服务器。 它看起来可以查看Heroku将使用哪个端口,如果在本地运行,则默认为3000。

⚠️The use of process.env.PORT || 3000 in the last line is important for deploying your app successfully ⚠️

⚠️process.env.PORT的使用process.env.PORT || 3000 最后一行process.env.PORT || 3000对成功部署您的应用很重要⚠️

If you save app.js and start the server with:

如果保存app.js并使用以下命令启动服务器:

$ node app.js

You can visit localhost:3000 in your browser and see for yourself the server is running.

您可以在浏览器中访问localhost:3000并亲自查看服务器是否正在运行。

创建您的静态文件 (Create your static files )

The next step is to create your static files. These are the HTML, CSS and JavaScript files you will serve up whenever a user visits your project.

下一步是创建静态文件。 这些是用户访问项目时将提供HTML,CSS和JavaScript文件。

Remember in app.js you told the express.static middleware to serve static files from the public directory.

请记住,在app.js您曾告诉express.static中间件从public目录提供静态文件。

The first step is of course to create such a directory and the files it will contain.

第一步当然是创建这样的目录及其将包含的文件。

$ mkdir public
$ cd public
$ touch index.html styles.css script.js

5. Edit the HTML file

5.编辑HTML文件

Open index.html in your preferred text editor. This will be the basic structure of the page you will serve to your visitors.

在首选的文本编辑器中打开index.html 。 这将是您将提供给访问者的页面的基本结构。

The example below creates a simple landing page for a Lorem Ipsum generator, but you can be as creative as you like here.

下面的示例为Lorem Ipsum生成器创建了一个简单的登录页面,但是您可以在这里发挥自己的创造力。

<!DOCTYPE html>
<head>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
	<link href="https://fonts.googleapis.com/css?family=Alegreya|Source+Sans+Pro&display=swap" rel="stylesheet">
	<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<html>
<body>
<h1>Lorem Ipsum generator</h1>
  <p>How many paragraphs do you want to generate?</p>
  <input type="number" id="quantity" min="1" max="20" value="1">
  <button id="generate">Generate</button>
  <button id="copy">Copy!</button>
<div id="lorem">
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>

6. Edit the CSS file

6.编辑CSS文件

Next up is editing the CSS file styles.css. Make sure this is linked in your HTML file.

接下来是编辑CSS文件styles.css 。 确保此链接在您HTML文件中。

The CSS below is for the Lorem Ipsum example. But again, feel free to be as creative as you want.

以下CSS用于Lorem Ipsum示例。 但同样,请随意发挥自己想要的创意。

h1 {
	font-family: 'Alegreya' ;
}

body {
	font-family: 'Source Sans Pro' ;
	width: 50%;
	margin-left: 25%;
	text-align: justify;
	line-height: 1.7;
	font-size: 18px;
}

input {
	font-size: 18px;
	text-align: center;
}

button {
	font-size: 18px;
	color: #fff;
}

#generate {
	background-color: #09f;
}

#copy {
	background-color: #0c6;
}

7. Edit the JavaScript file

7.编辑JavaScript文件

Finally, you might want to edit the JavaScript file script.js. This will let you make your page more interactive.

最后,您可能需要编辑JavaScript文件script.js 。 这将使您的页面更具交互性。

The code below defines two basic functions for the Lorem Ipsum generator. Yes, I used JQuery - it's quick and easy to work with.

以下代码定义了Lorem Ipsum生成器的两个基本功能。 是的,我使用了JQuery-使用起来快速简便。

$("#generate").click(function(){
	var lorem = $("#lorem");
	lorem.html("");
	var quantity = $("#quantity")[0].valueAsNumber;
	var data = ["Lorem ipsum", "quia dolor sit", "amet", "consectetur"];
	for(var i = 0; i < quantity; i++){
		lorem.append("<p>"+data[i]+"</p>");
	}
})

$("#copy").click(function() {
	var range = document.createRange();
	range.selectNode($("#lorem")[0]);
	window.getSelection().removeAllRanges();
	window.getSelection().addRange(range);
	document.execCommand("copy");
	window.getSelection().removeAllRanges();
	}
)

Note that here, the data list is truncated to make it easier to show. In the actual app, it is a much longer list of full paragraphs. You can see the entire file in the repo, or look here for the original source.

请注意,此处data列表被截断以使其更易于显示。 在实际的应用程序中,它是完整段落的更长列表。 您可以在存储库中查看整个文件,或在此处查找原始源

部署您的应用 (Deploying your app)

After writing your static code and checking it all works as expected, you can get ready to deploy to Heroku.

在编写完静态代码并检查了所有代码后,它们可以按预期工作,即可开始部署到Heroku。

However, there are a couple more things to do.

但是,还有更多事情要做。

8. Create a Procfile

8.创建一个Procfile

Heroku will need a Procfile to know how to run your app.

Heroku将需要一个Procfile来知道如何运行您的应用程序。

A Procfile is a "process file" which tells Heroku which command to run in order to manage a given process. In this case, the command will tell Heroku how to start your server listening on the web.

Procfile是一个“进程文件”,它告诉Heroku为了管理给定进程而运行哪个命令。 在这种情况下,该命令将告诉Heroku如何启动您的服务器在Web上侦听。

Use the command below to create the file.

使用下面的命令创建文件。

⚠️This is an important step, because without a Procfile, Heroku cannot put your server online. ⚠️

⚠️这是重要的一步,因为没有Procfile,Heroku无法使您的服务器联机。 ⚠️

$ echo "web: node app.js" > Procfile

Notice that the Procfile has no file extension (e.g., ".txt", ".json").

请注意,Procfile没有文件扩展名(例如,“。txt”,“。json”)。

Also, see how the command node app.js is the same one used locally to run your server.

另外,请查看命令node app.js与本地用于运行服务器的命令如何相同。

9. Add and commit files to Git

9.添加文件并将其提交到Git

Remember you initiated a Git repository when setting up. Perhaps you have been adding and committing files as you have gone.

请记住,设置时您启动了一个Git存储库。 也许您一直在添加和提交文件。

Before you deploy to Heroku, make sure to add all the relevant files and commit them.

在部署到Heroku之前,请确保添加所有相关文件并提交。

$ git add .
$ git commit -m "ready to deploy"

The final step is to push to your Heroku master branch.

最后一步是推送到您的Heroku master分支。

$ git push heroku master

You should see the command line print out a load of information as Heroku builds and deploys your app.

您应该在Heroku构建和部署应用程序时看到命令行打印出大量信息。

The line to look for is: Verifying deploy... done.

寻找的行是: Verifying deploy... done.

This shows that your build was successful.

这表明您的构建成功。

Now you can open the browser and visit your-project-name.herokuapp.com. Your app will be hosted on the web for all to visit!

现在,您可以打开浏览器并访问your-project-name.herokuapp.com。 您的应用程序将托管在网络上,供所有人访问!

快速回顾 (Quick recap)

Below are the steps to follow to deploy a simple Express app to Heroku:

以下是将简单的Express应用程序部署到Heroku的步骤:

  1. Create a new directory and initialise a Git repository

    创建一个新目录并初始化一个Git存储库
  2. Login to the Heroku CLI and create a new project

    登录到Heroku CLI并创建一个新项目
  3. Initialise a new npm project and install Express.js

    初始化一个新的npm项目并安装Express.js
  4. Edit the contents of app.js

    编辑app.js的内容
  5. Edit the static HTML, CSS and JavaScript files

    编辑静态HTML,CSS和JavaScript文件
  6. Create a Procfile

    创建一个Procfile
  7. Add and commit to Git, then push to your Heroku master branch

    添加并提交到Git,然后推送到您的Heroku master分支

检查您的应用程序是否无法正常工作的事情 (Things to check if your app is not working)

Sometimes, despite best intentions, tutorials on the Internet don't work exactly as you expected.

有时,尽管有最好的意图,但Internet上的教程并不能完全按照您的预期工作。

The steps below should help debug some common errors you might encounter:

以下步骤应有助于调试您可能遇到的一些常见错误:

  • Did you initialise a Git repo in your project folder? Check if you ran git init earlier. Heroku relies on Git to deploy code from your local machine.

    您是否在项目文件夹中初始化了一个Git存储库? 检查您是否较早运行了git init 。 Heroku依靠Git从本地计算机部署代码。

  • Did you create a package.json file? Check if you ran npm init -y earlier. Heroku requires a package.json file to recognise this is a Node.js project.

    您是否创建了package.json文件? 检查您是否较早运行了npm init -y 。 Heroku需要package.json文件来识别这是一个Node.js项目。

  • Is the server running? Make sure your Procfile uses the correct file name to start the server. Check you have web: node app.js and not web: node index.js.

    服务器正在运行吗? 确保您的Procfile使用正确的文件名来启动服务器。 检查您是否具有web: node app.js而不是web: node index.js

  • Does Heroku know which port to listen on? Check you used app.listen(process.env.PORT || 3000) in your app.js file.

    Heroku知道要监听哪个端口吗? 检查您在app.js文件中是否使用过app.listen(process.env.PORT || 3000)

  • Do your static files have any errors in them? Check them by running locally and seeing if there are any bugs.

    您的静态文件中是否有任何错误? 通过在本地运行并检查是否存在任何错误来检查它们。

Thanks for reading - if you made it this far, you might want to checkout the finished version of the demo project.

感谢您的阅读-如果您到目前为止做的不错,则可能要出演示项目的完成版本

翻译自: https://www.freecodecamp.org/news/how-to-deploy-your-site-using-express-and-heroku/

heroku

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将Express+Vue3+Vite应用程序发布为独立的Web应用,您可以按照以下步骤进行操作: 1. 在本地开发环境中构建Vue3应用程序。在项目根目录下打开终端或命令提示符,运行以下命令: ```bash npm run build ``` 这将使用Vite构建工具编译和打包Vue3应用程序,并将生成的静态文件保存在`dist`目录中。 2. 创建一个Express服务器来托管Vue3应用程序。在项目根目录下创建一个名为`server.js`的文件,并添加以下内容: ```javascript const express = require('express'); const path = require('path'); const app = express(); // 静态文件托管 app.use(express.static(path.join(__dirname, 'dist'))); // 所有路由重定向到index.html app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'dist', 'index.html')); }); // 启动服务器 const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Server is running on port ${port}`); }); ``` 在上述示例中,我们使用Express创建了一个简单的服务器。我们通过`express.static`中间件来托管生成的静态文件,然后将所有路由重定向到`index.html`以支持Vue的单页应用。最后,我们使用`app.listen`方法来启动服务器,并指定端口号。 3. 在项目根目录下打开终端或命令提示符,运行以下命令启动Express服务器: ```bash node server.js ``` 这将在本地启动Express服务器,并监听指定的端口(默认为3000)。 4. 现在,您的Express+Vue3+Vite应用程序已经作为一个独立的Web应用在本地运行起来了。您可以在浏览器中访问`http://localhost:3000`来查看应用程序。 5. 要将应用程序部署到生产环境,您可以选择将静态文件和服务器文件上传到云服务器或托管平台,如AWS、Azure、Heroku等。具体的部署步骤将取决于您选择的部署平台。 请注意,上述示例仅提供了一个简单的发布流程,并且假设您已经拥有一个可用的服务器用于托管应用程序。在实际部署过程中,您可能还需要考虑安全性、性能优化、域名绑定等方面的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值