node.js 静态属性
This tutorial will show you how to convert a static website that uses HTML, CSS and JavaScript (JS) to a dynamic one using MongoDB, Express, Static HTML, CSS, JS, and Node.js.
本教程将向您展示如何使用MongoDB,Express,静态HTML,CSS,JS和Node.js将使用HTML,CSS和JavaScript(JS)的静态网站转换为动态网站。
Our tech stack will be similar to the popular MEAN/MERN stack (MongoDB, Express, Angular or React, and NodeJS). But instead of using Angular or React, we will use a templating engine called EJS (Embedded JavaScript.)
我们的技术堆栈将类似于流行的MEAN / MERN堆栈(MongoDB,Express,Angular或React和NodeJS)。 但是,我们将使用名为EJS (嵌入式JavaScript)的模板引擎,而不是使用Angular或React。
Other popular templating engines include Handlebars, Pug, and Nunjucks.
其他流行的模板引擎包括Handlebars,Pug和Nunjucks。
Afterwards, we will deploy our Node.js web app to DigitalOcean and cover domain names, SSL, reverse proxies, and process managers.
然后,我们将Node.js Web应用程序部署到DigitalOcean,并涵盖域名,SSL,反向代理和流程管理器。
Learning a templating language can be easier than a JS framework. You can just write HTML, and it lets you insert the same piece of code in multiple locations (called partials) or pass server-side variables to be displayed on the front-end (such as a username).
学习模板语言比JS框架容易。 您只需编写HTML,它就可以将同一段代码插入多个位置(称为“局部”),或传递要在前端显示的服务器端变量(例如用户名)。
目录 (Table of Contents)
开发您的第一个Node.js Web应用程序 (Developing Your First Node.js Web App)
安装Node.js (Installing Node.js)
First, make sure you’ve installed Node.js on your local machine or VPS hosting provider. If you haven’t installed it, go to the Node.js website to do so.
首先,请确保已在本地计算机或VPS托管提供商上安装了Node.js。 如果尚未安装,请访问Node.js网站 。
With Node.js, you can write server-side code using a special form of JavaScript so you can use an already familiar language.
使用Node.js,您可以使用特殊形式JavaScript编写服务器端代码,以便可以使用已经熟悉的语言。
The Node.js installer comes bundled with the package manager NPM. NPM is a repository for Node Modules, reusable pieces of code that can extend the functionality of your server. It’s similar to a plugin repository, and Node Modules can be thought of as code snippets or libraries (depending on how large they are).
Node.js安装程序与软件包管理器NPM捆绑在一起。 NPM是节点模块(可重复使用的代码段,可以扩展服务器功能)的存储库。 它类似于插件存储库,并且可以将Node Modules视为代码段或库(取决于它们的大小)。
Windows Users: Need to add Node and NPM to their PATH so they can call them easily on the command line. For more in-depth instructions, see my guide here.
Windows用户:需要将Node和NPM添加到其PATH中,以便他们可以在命令行上轻松调用它们。 有关更深入的说明,请参阅此处的指南 。
测试安装 (Testing the Install)
To test that the installation has worked correctly, open a terminal window, and type node -v
and npm -v
. If the resulting message starts with a v and is followed by some numbers (indicating a version), then the installation has been successful. Now you’re ready to create your first server.
要测试安装是否正常工作,请打开终端窗口,然后输入node -v
和npm -v
。 如果生成的消息以av开头,并带有一些数字(表示版本),则表明安装成功。 现在,您可以创建第一个服务器了。
创建您的第一台服务器 (Creating Your First Server)
Once you have created a static website, the first step in creating a Node.js app is to create an Express web server.
创建静态网站后,创建Node.js应用程序的第一步是创建Express Web服务器。
First, move all your website’s static files (HTML, CSS, JS, images, etc.) into a folder called public and create a file called server.js in the root directory of your website folder. In the server.js file type:
首先,将网站的所有静态文件(HTML,CSS,JS,图像等)移动到名为public的文件夹中,并在网站文件夹的根目录中创建一个名为server.js的文件。 在server.js文件中,输入:
// Load Node modules
var express = require('express');
// Initialise Express
var app = express();
// Render static files
app.use(express.static('public'));
// Port website will run on
app.listen(8080);
Then in the terminal, type: npm init
. Press enter to accept the default parameters for all the following options, but make sure the entry point is server.js.
然后在终端中输入: npm init
。 按Enter接受以下所有选项的默认参数,但请确保入口点是server.js。
Finally, type: npm start
and then go to the IP Address of your VPS host, or localhost:8080/index.html (or the name of one of your webpages) in the browser. The Express server you just created should now be serving your website’s static files.
最后,键入: npm start
,然后在浏览器中转到您的VPS主机的IP地址或localhost:8080 / index.html(或其中一个网页的名称)。 您刚才创建的Express服务器现在应该正在提供网站的静态文件。
下一步 (Next Steps)
Moving forward, we will discuss how to convert your static files to dynamic ones using the EJS templating engine. Then we'll look at how to copy repeated code using partials and inject server-side variables to the front-end.
展望未来,我们将讨论如何使用EJS模板引擎将静态文件转换为动态文件。 然后,我们将研究如何使用partials复制重复的代码以及如何将服务器端变量注入前端。
模板基础 (Templating Basics)
安装EJS (Installing EJS)
The first step to use EJS is to install it. A simple npm install ejs --save
will do the trick. The --save
parameter saves the module to the package.json
file.
使用EJS的第一步是安装它。 一个简单的npm install ejs --save
就能解决问题。 --save
参数将模块保存到package.json
文件。
This makes it so anyone who clones the git repo (or otherwise downloads the site's files) can install all the required Node modules for the project (called dependencies) using the npm install
command instead. Then they don't have to type npm install (module name)
for however many modules they need.
这样一来,克隆git repo(或下载站点文件)的任何人都可以使用npm install
命令npm install
项目所需的所有必需Node模块(称为依赖项)。 然后,他们不必为所需的许多模块键入npm install (module name)
。
将静态页面转换为EJS文件 (Converting Static Pages to EJS Files)
Next, you need to convert your static HTML files into dynamic EJS ones and set up your folder structure in the way EJS expects.
接下来,您需要将静态HTML文件转换为动态EJS文件,并按照EJS期望的方式设置文件夹结构。
In the root directory of your website, create a folder called views. Inside that folder create two sub-folders called pages and partials. Move all your HTML files into the pages sub-folder and rename the .html file extensions to .ejs.
在网站的根目录中,创建一个名为views的文件夹。 在该文件夹内,创建两个名为pages和partials的子文件夹。 将所有HTML文件移动到pages子文件夹中,并将.html文件扩展名重命名为.ejs。
Your folder structure should look similar to the picture below.
您的文件夹结构应类似于下图。
重用代码-创建您的第一个EJS部分 (Reusing Code - Creating Your First EJS Partial)
When creating static sites, there's often code that you repeat on every page such as the head (where the meta tags are located), header, and footer sections.
创建静态网站时,通常会在每个页面上重复执行一些代码,例如标题(位于meta标签所在的位置),页眉和页脚部分。
It's inconvenient to change them on every page (especially on larger sites) if alterations are needed. But if you use EJS partials then you won't have to. Editing one template (partial) file will update the code on every page that the file is included in.
如果需要更改,则在每个页面上(尤其是在较大的站点上)进行更改都是不方便的。 但是,如果您使用EJS局部函数,则不必这样做。 编辑一个模板(部分)文件将更新包含该文件的每一页上的代码。
We'll take a typical part of a website to be templated, the header, as an example. Create a new file called header.ejs in the partials folder. Copy and paste all the code between the <header></header>
tags on one of your EJS pages into it.
我们将以要模板化的网站的典型部分(标题)为例。 在partials文件夹中创建一个名为header.ejs的新文件。 将其中一个EJS页面上<header></header>
标记之间的所有代码复制并粘贴到其中。
Finally, on all pages with a header delete the code between the <header></header>
tags (the same code you copied to the header.ejs partial file) and replace it with <% include('../partials/header') %>
. Now, you've created your first EJS partial. Repeat the process for any other repetitive pieces of code such as the head and footer sections.
最后,在所有带有标题的页面上,删除<header></header>
标记之间的代码(与复制到header.ejs部分文件中的代码相同),然后将其替换为<% include('../partials/header') %>
。 现在,您已经创建了第一个EJS部分。 对其他重复的代码段(例如,页眉和页脚部分)重复此过程。
Small Tip: If you find it hard to differentiate between your pages and partials since they have the same .ejs file extension, it can be helpful to put an underscore _ in front of the names of partials (so _ header.ejs). This is a naming convention that some developers use that can be helpful.
小提示:如果由于页面和分页具有相同的.ejs文件扩展名而难以区分,则在分页名称前加下划线_很有帮助(因此_ header.ejs)。 这是一些开发人员使用的命名约定,可能会有所帮助。
渲染EJS页面 (Rendering EJS Pages)
Now we get to the exciting part: making the server render the EJS pages and partials so you can see them on the front-end.
现在,我们进入令人兴奋的部分:使服务器呈现EJS页面和部分,以便您可以在前端看到它们。
server.js Example
server.js示例
// Load Node modules
var express = require('express');
const ejs = require('ejs');
// Initialise Express
var app = express();
// Render static files
app.use(express.static('public'));
// Set the view engine to ejs
app.set('view engine', 'ejs');
// Port website will run on
app.listen(8080);
// *** GET Routes - display pages ***
// Root Route
app.get('/', function (req, res) {
res.render('pages/index');
});
First, we need to add the EJS Node module to our server. So, in the server.js
file (see example above), add const ejs = require('ejs');
.
首先,我们需要将EJS Node模块添加到我们的服务器。 因此,在server.js
文件中(请参见上面的示例),添加const ejs = require('ejs');
。
Second, we need to tell our Express server to use EJS so add app.set('view engine', 'ejs');
.
其次,我们需要告诉Express服务器使用EJS,因此添加app.set('view engine', 'ejs');
。
Now, we need to configure routes. Routes tell the server what to do when a user goes to a certain URL in your website such as http://testapp.com/login
.
现在,我们需要配置路由。 路由告诉服务器,当用户转到您网站中的某个URL(例如http://testapp.com/login
时该怎么做。
There are two types of routes, GET and POST. GET routes display pages and POST routes upload data from the front-end to the server (usually via a form) typically before a page is rendered and the uploaded data is somehow used.
路由有两种类型,即GET和POST。 GET路由显示页面,而POST路由通常在呈现页面和以某种方式使用上传数据之前,将数据从前端上传到服务器(通常通过表单)。
Since we only want to display our EJS pages, we will just use GET routes. Add them after the app.listen(8080)
line in server.js
. For the index page, the route will be:
因为我们只想显示我们的EJS页面,所以我们只使用GET路由。 在server.js
的app.listen(8080)
行之后添加它们。 对于索引页面,路由将为:
// *** GET Routes - display pages ***
// Root Route
app.get('/', function (req, res) {
res.render('pages/index');
});
The '/' specifies the URL of the website the code will activate on, the req
stands for request and res
for response. So, the response returned when going to http://testapp.com
is rendering (displaying to the browser) the pages/index.ejs page. Add similar routes for your other EJS pages.
“ /”指定将在其上激活代码的网站的URL, req
代表请求, res
代表响应。 因此,访问http://testapp.com
时返回的响应正在渲染(显示到浏览器)pages / index.ejs页面。 为其他EJS页面添加类似的路线。
将服务器端数据传递到前端 (Passing Server-Side Data to the Frontend)
The main attraction of templating, apart from reusing code, is that you can pass server-side variables to the front-end. Either a single variable like the current user's username, or an array, like the details of every registered user.
除了重用代码外,模板化的主要吸引力在于,您可以将服务器端变量传递给前端。 单个变量(例如当前用户的用户名)或数组(例如每个注册用户的详细信息)。
However, the real strength of passing server-side variables becomes apparent when using APIs or databases.
但是,使用API或数据库时,传递服务器端变量的真正优势显而易见。
For a basic example, the below code will display "Louise" in the h2 tag of the index page:
对于一个基本示例,以下代码将在索引页的h2标签中显示“ Louise”:
server.js
server.js
// Route Route
app.get('/', function (req, res) {
var name = "Louise";
// Render index page
res.render('pages/index', {
// EJS variable and server-side variable
name: name
});
});
The first name
is the name of the EJS variable (the name for displaying it on the front-end), and the second is the variable that contains the data you want to send. (They don't have to be identical.)
第一个name
是EJS变量的名称(用于在前端显示它的名称),第二个名称是包含要发送的数据的变量。 (它们不必相同。)
index.ejs
index.ejs
<h2>My name is <%= name %></h2>
For a simple array, you can use this example instead, which will create a p tag for every name in the listnames variable:
对于一个简单的数组,可以改用以下示例,它将为listnames变量中的每个名称创建ap标签:
server.js
server.js
// Route Route
app.get('/', function (req, res) {
var listnames = ["Louise", "Sadie", "Erik", "Raph", "Gina"];
// Render index page
res.render('pages/index', {
// EJS variable and server-side variable
listnames: listnames
});
});
index.ejs
index.ejs
<% listnames.forEach(function(name) { %>
<p><%= name %></p>
<% }); %>
Congratulations. You’ve finished developing your first Node.js web app. In the next part, we will see how we can make it live (deploy it) on the web so you can show it off.
恭喜你 您已经完成了第一个Node.js Web应用程序的开发。 在下一部分中,我们将看到如何在网络上实时发布(部署)它,以便您可以展示它。
部署第一个Node.js Web应用程序 (Deploying Your First Node.js Web App)
There are many hosting platforms you can use to deploy your Node.js web apps such as Section, Heroku, Vultr, Linode, Google Cloud Platform and Amazon Web Services.
您可以使用许多托管平台来部署Node.js Web应用程序,例如Section , Heroku , Vultr , Linode , Google Cloud Platform和Amazon Web Services 。
In this walk-through, we will be using DigitalOcean to deploy our Node.js app.
在本演练中 ,我们将使用DigitalOcean部署Node.js应用程序。
设置DigitalOcean (Setting up DigitalOcean)
First, create an account on the DigitalOcean platform. There are discount codes available to add free credit to your account such as the code available in the Github Student Developer Pack. Be aware that you can only redeem one code per account.
首先,在DigitalOcean平台上创建一个帐户。 有一些折扣代码可用来向您的帐户添加免费信用,例如Github Student Developer Pack中提供的代码。 请注意,每个帐户只能兑换一个代码。
Second, you need to create a droplet. A droplet is a VPS (Virtual Private Server.) It’s similar to a Linux VM which is hosted on a server farm somewhere.
其次,您需要创建一个小滴。 Droplet是VPS(虚拟专用服务器)。它类似于Linux VM,后者托管在某个服务器场中。
Once you’ve logged into your account, go to droplets under the Manage heading and click create and then droplets.
登录帐户后,转到“管理”标题下的小滴,然后依次单击“创建”和“小滴”。
You can leave most of the settings as the default but change the plan to the basic $5 a month which contains enough resources for your app. You can scale this up later if needed.
您可以将大多数设置保留为默认设置,但可以将计划更改为基本每月5美元,其中包含适用于您应用的足够资源。 如果需要,您可以稍后扩大规模。
Also, choose the datacenter closest to the target audience of your app and change the authentication to password. While password authentication is less secure (SSH Keys is recommended), it’s much easier to set up. So, for demonstration purposes, we’ll use this method.
另外,选择最接近应用程序目标受众的数据中心,然后将身份验证更改为密码。 尽管密码身份验证的安全性较低(建议使用SSH密钥),但设置起来却容易得多。 因此,出于演示目的,我们将使用此方法。
All that’s left now is to pick a name (hostname) and click Create Droplet.
现在剩下的就是选择一个名称(主机名),然后单击“创建Droplet”。
连接到您的Droplet (Connecting to your Droplet)
Shortly afterward, you’ll receive an email containing the username and password of your droplet which you’ll use to login.
此后不久,您将收到一封电子邮件,其中包含您用于登录的Droplet的用户名和密码。
Back on the DigitalOcean website, under droplets, click the name of your newly created droplet, and then click on Console. This will open a new tab that will let you control your droplet.
返回DigitalOcean网站上的小滴下,单击新创建的小滴的名称,然后单击控制台。 这将打开一个新标签,让您控制液滴。
Alternatively, you can use any SSH client with the IP address and user credentials contained in the email.
或者,您可以将任何SSH客户端与电子邮件中包含的IP地址和用户凭据一起使用。
On your first login, since you used password authentication, it will prompt you to set a new password. A great way to generate secure passwords and store them is a password manager like LastPass.
首次登录时,由于使用了密码认证,因此会提示您设置新密码。 生成安全密码并存储它们的一种好方法是使用密码管理器,例如LastPass 。
部署Node.js Web应用程序 (Deploying Your Node.js Web App)
First, you’ll need to copy the code for your web app to your droplet. If you’re using source control such as Git, then it’s as simple as installing git using apt-get install git -y
and then using the git clone command git clone (link to your repository)
, adding the link to your repository at the end.
首先,您需要将Web应用程序的代码复制到Droplet中。 如果您使用的是Git之类的源代码控制,则就像使用apt-get install git -y
,然后使用git clone命令git clone (link to your repository)
,将链接添加到存储库中结束。
Second, you’ll need to install Node. Type:
其次,您需要安装Node。 类型:
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs
Third, you'll need to navigate to the folder containing your web app. Type ls and then enter to view all the folders in your current working directory (location). This will look like the image below:
第三,您需要导航到包含您的Web应用程序的文件夹。 键入ls,然后输入以查看当前工作目录(位置)中的所有文件夹。 如下图所示:
Type cd and then the name of the folder that appears. Type ls again and you should see the files in your web app's root directory.
键入cd,然后键入出现的文件夹的名称。 再次键入ls,您应该在Web应用程序的根目录中看到文件。
Next, you’ll need to install the node modules (dependencies) for your web app. If you installed all your modules with -save
at the end, which saves them to the package.json file, then just type npm install
and press enter.
接下来,您需要为Web应用程序安装节点模块(依赖项)。 如果您在所有模块的末尾都安装了-save
,则将它们保存到package.json文件中,则只需键入npm install
并按Enter。
If not, when you run npm start
an error will appear with module not found. Type npm install (module name)
and press enter and then try running npm start
again. Repeat the process until the error disappears.
否则,当您运行npm start
,将出现一个错误,提示找不到模块。 键入npm install (module name)
,然后按Enter,然后尝试再次运行npm start
。 重复该过程,直到错误消失。
If you need to install MongoDB (if you’ve created a MongoDB database), then follow these instructions.
如果您需要安装MongoDB(如果您已经创建了MongoDB数据库),请按照以下说明进行操作 。
Finally, type npm start
to start your web app. Now that your web app is running, in a new browser tab, type the IP Address of your droplet (found in the email that DigitalOcean sent when you created the droplet) followed by a colon and the port your app runs on. For example, 167.172.54.51:8080
.
最后,键入npm start
启动您的Web应用程序。 现在,您的Web应用程序已运行,在新的浏览器选项卡中,键入Droplet的IP地址(在创建Droplet时DigitalOcean发送的电子邮件中找到),后跟冒号和运行应用程序的端口。 例如167.172.54.51:8080
。
If you’re using an Express web server (which if you followed my getting started with Node.js guide, you did), you’ll find the port number located in the app.listen()
line inside the server.js file. For example, app.listen(8080)
which is a common port used.
如果您使用的是Express Web服务器(如果您按照我的Node.js入门指南进行操作),则会在server.js文件内的app.listen()
行中找到端口号。 例如, app.listen(8080)
是常用端口。
Congratulations, your first Node.js web app should be displayed in your web browser which is running on your DigitalOcean droplet.
恭喜,您的第一个Node.js Web应用程序应显示在运行在DigitalOcean Droplet上的Web浏览器中。
配置域名 (Configuring Your Domain Name)
You typed in an IP Address and port number to view your web app but, wouldn't you prefer a custom domain name like yourapp.com?
您输入了IP地址和端口号以查看Web应用程序,但是,您是否不希望使用自定义域名,例如yourapp.com?
Assuming you’ve already bought a domain, the first step is to add a DNS record so your domain name will resolve to the IP address of your DigitalOcean droplet. A DNS record tells your browser what to do when they load your domain. In this case, it should go to the IP address of your droplet.
假设您已经购买了一个域名,第一步是添加DNS记录,以便您的域名将解析为DigitalOcean Droplet的IP地址。 DNS记录告诉您的浏览器在加载您的域时该怎么做。 在这种情况下,它应该转到小滴的IP地址。
If you’ve not bought a domain, domain registrars like Namecheap sell domain names and often other services such as email and static/CMS hosting, though there are benefits to going with a dedicated hosting and email provider.
如果您还没有购买域名,那么诸如Namecheap之类的域名注册商会出售域名,通常还会出售其他服务,例如电子邮件和静态/ CMS托管,尽管与专用托管和电子邮件提供商合作有很多好处。
Netlify offers hosting for static sites and SiteGround for CMS websites. Office365 and GSuite are the kings of custom email providers. See my guide for Setting Up a Professional Email to read a comparison of Office365 and GSuite.
Netlify提供静态网站托管和SiteGround CMS网站托管。 Office365和GSuite是自定义电子邮件提供商的王者。 请参阅我的《 设置专业电子邮件指南》以阅读Office365和GSuite的比较。
Login to your domain registrar and go to the advanced DNS settings of your domain. For example, on Namecheap, it’s the Advanced DNS tab on the Manage Domain screen.
登录到您的域名注册商,然后转到您的域的高级DNS设置。 例如,在Namecheap上,它是“管理域”屏幕上的“高级DNS”选项卡。
You want to add a new record as follows: the type should be set to A, the host should be either @ or blank (depending on your provider), and the value should be the IP Address of your droplet. Repeat the process for the host www which will do the same for the www version of your domain.
您要添加新记录,如下所示:类型应设置为A,主机应为@或为空(取决于您的提供程序),值应为Droplet的IP地址。 对主机www重复此过程,该过程将与您的域的www版本相同。
It can take up to 24-48hrs for the changes to process, but it’s usually between 15 minutes to an hour. A quick way to check when it’s done is to go to DNSChecker. Type in your domain name and make sure the type is set to A. When the result comes back as the IP Address of your droplet, then you’ve connected your domain successfully.
更改过程最多可能需要24-48小时,但通常需要15分钟到一个小时。 一种检查完成时间的快速方法是转到DNSChecker 。 输入您的域名,并确保将类型设置为A。当结果返回为Droplet的IP地址时,表示您已成功连接域。
The final test is to type your domain name followed by a colon and then the port number (e.g. yourdomain.com:8080
). You should now see your web app loading.
最后的测试是键入您的域名,后跟冒号,然后输入端口号(例如yourdomain.com:8080
)。 现在,您应该看到Web应用程序正在加载。
从您的URL中删除端口号 (Removing the Port Number from your URL)
Now that you’ve got a cool domain name hooked up to your web app, you’ll probably want to remove that pesky port number.
现在,您已经将很酷的域名连接到了Web应用程序,您可能想要删除该讨厌的端口号。
We can do this by setting up what’s called a reverse proxy. A reverse proxy will tell your droplet when a user goes to yourdomain.com, it should serve the site at yourdomain.com:8080. We will use the popular reverse proxy Nginx to do so.
我们可以通过设置反向代理来实现。 反向代理将在用户访问yourdomain.com时告诉您的Droplet,它应在yourdomain.com:8080上为网站提供服务。 我们将使用流行的反向代理Nginx来这样做。
The first step is to install Nginx. Type the following to update your package list (so you can get the latest version) and install Nginx:
第一步是安装Nginx。 输入以下内容以更新您的软件包列表(以便获取最新版本)并安装Nginx:
sudo apt-get update
sudo apt-get install nginx
Since DigitalOcean droplets are created with a firewall enabled, you’ll have to allow Nginx through it so it can work properly. sudo ufw allow 'Nginx Full'
will do this.
由于DigitalOcean小滴是在启用防火墙的情况下创建的,因此您必须允许Nginx通过它才能正常工作。 sudo ufw allow 'Nginx Full'
将执行此操作。
To check the installation has gone smoothly, go to the http version of your domain name e.g. http://yourdomain.com
. If you see a Welcome to Nginx landing page, then it’s been successful.
要检查安装是否顺利,请转到域名的http版本,例如http://yourdomain.com
。 如果看到“欢迎使用Nginx”登录页面,则说明成功。
The second step is to secure your reverse proxy. Currently going to https://yourdomain.com
won’t work. That’s because we haven’t configured SSL yet, and we need to install a package called Certbot to do so.
第二步是保护反向代理。 目前无法访问https://yourdomain.com
。 这是因为我们尚未配置SSL,因此需要安装一个名为Certbot的软件包。
To install Certbot, type the following to ensure you get the latest version:
要安装Certbot,请键入以下内容以确保获得最新版本:
sudo add-apt-repository ppa:certbot/certbot
sudo apt-get install python-certbot-nginx
Next, you need to add your domain to Nginx so Certbot can generate a certificate to the correct domain. Open the configuration file using sudo nano /etc/nginx/sites-available/default
and replace the underscores in the server_name line to your domain. For example, server_name yourdomain.com www.yourdomain.com;
. Save the file and exit by typing CTRL+x, y and then enter.
接下来,您需要将域添加到Nginx,以便Certbot可以为正确的域生成证书。 使用sudo nano /etc/nginx/sites-available/default
打开配置文件,并将server_name行中的下划线替换为您的域。 例如, server_name yourdomain.com www.yourdomain.com;
。 保存文件并通过键入CTRL + x,y退出,然后输入。
To test that there are no errors in the file, type sudo nginx -t
and if there’s none, type sudo systemctl reload nginx
to reload Nginx so it will use the updated configuration.
要测试文件中是否没有错误,请键入sudo nginx -t
,如果没有错误,请键入sudo systemctl reload nginx
重新加载Nginx,以便它将使用更新后的配置。
Now we just need to generate the SSL certificate. sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
will start the process. You should choose option 2 for the redirect process because it will forward anyone trying to access the insecure version of your site (http) to the secure (https) version instead.
现在我们只需要生成SSL证书即可。 sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
将启动该过程。 您应该为重定向过程选择选项2,因为它将把尝试访问站点(http)的不安全版本的任何人转发到安全(https)版本。
To test this, go to https://yourdomain.com
and you should see the Nginx Welcome screen again.
要进行测试,请访问https://yourdomain.com
,您应该再次看到Nginx欢迎屏幕。
Finally, we're onto the last step, adding the Nginx configuration for your web app. For demonstration purposes, we'll just modify the default one instead of creating a new one specifically for your web app. If you need to host several web apps on one droplet, you'd need to add a new configuration for each site.
最后,我们进入最后一步,为您的Web应用程序添加Nginx配置。 出于演示目的,我们将只修改默认值,而不是专门为您的Web应用程序创建一个新值。 如果您需要在一个Droplet上托管多个Web应用程序,则需要为每个站点添加一个新配置。
Type: sudo nano /etc/nginx/sites-available/default
to edit the default configuration file.
键入: sudo nano /etc/nginx/sites-available/default
以编辑默认配置文件。
You need to change the server_name
parameter to the name of your domain. For example: yourdomain.com. Under location /, proxy_pass
should be changed to http://localhost:(port name)
. The ssl_certificate_key
should be modified: /etc/letsencrypt/live/(domain name)/privkey.pem
. Finally, add the code block below to the end of the file and then type CTRL+X, and then y to exit.
您需要将server_name
参数更改为您的域的名称。 例如:yourdomain.com。 在位置/下, proxy_pass
应该更改为http://localhost:(port name)
。 ssl_certificate_key
应该被修改: /etc/letsencrypt/live/(domain name)/privkey.pem
。 最后,将下面的代码块添加到文件末尾,然后键入CTRL + X,然后键入y退出。
server {
if ($host = auroraspotter.space) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80 default_server;
listen [::]:80 default_server;
server_name auroraspotter.space;
return 404; # managed by Certbot
Here's a complete example of what it should look like. Note: the server_name
should be the name of your domain.
这是一个完整的示例。 注意: server_name
应该是您的域的名称。
server {
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name auroraspotter.space;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://localhost:8080;
proxy_set_header Host $http_host;
proxy_cache_bypass $http_upgrade;
proxy_redirect off;
}
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/auroraspotter.space/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/auroraspotter.space/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = auroraspotter.space) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80 default_server;
listen [::]:80 default_server;
server_name auroraspotter.space;
return 404; # managed by Certbot
To test that there are no errors in the file, type sudo nginx -t
. If there’s none, type sudo systemctl reload nginx
to reload Nginx so it will use the updated configuration.
要测试文件中是否没有错误,请输入sudo nginx -t
。 如果不存在,请键入sudo systemctl reload nginx
以重新加载Nginx,以便它将使用更新的配置。
Finally, you should be able to go to yourdomain.com and your web app will be running.
最后,您应该能够访问yourdomain.com,并且您的网络应用将开始运行。
在启动时运行应用程序(设置进程管理器) (Running the App on Boot (Setting up a Process Manager))
You've hooked your domain name up to your droplet and configured Nginx to serve your web app, but how do you keep it running all the time especially after restarting your droplet?
您已经将域名挂接到了Droplet上,并配置了Nginx来为您的Web应用程序提供服务,但是如何使它始终保持运行,特别是在重新启动Droplet之后呢?
That's where a process manager comes in. It will manage your Node.js web app, log any errors, and start/stop it as needed. We will be using the process manager called PM2.
这就是流程管理器的用武之地。它将管理您的Node.js Web应用程序,记录所有错误,然后根据需要启动/停止它。 我们将使用名为PM2的流程管理器。
The first step is to install PM2 using sudo npm install pm2@latest -g
. Next, to run it on boot, run pm2 startup systemd
. It should say to setup the startup script, copy and paste the following command which will be sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u (username) --hp /home/(username)
.
第一步是使用sudo npm install pm2@latest -g
安装PM2。 接下来,要在启动时运行它,请运行pm2 startup systemd
。 应该说要设置启动脚本,复制并粘贴以下命令,它将是sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u (username) --hp /home/(username)
If you're using the default login that DigitalOcean provided, this will be root. Type this into the terminal and press enter. If it says command successfully executed (like below) then it has worked.
如果您使用DigitalOcean提供的默认登录名,则该登录名将是root。 在终端中输入,然后按Enter。 如果它说命令成功执行(如下所示),则说明它已经起作用。
[ 'systemctl enable pm2-root' ]
[PM2] Writing init configuration in /etc/systemd/system/pm2-root.service
[PM2] Making script booting at startup...
[PM2] [-] Executing: systemctl enable pm2-root...
[PM2] [v] Command successfully executed.
Using the cd command, navigate to the folder of your web app. Then type pm2 start server.js
. This will start the web app using pm2. Afterward, type pm2 save
which will save it to be started on boot. If it says successfully saved, then it's been saved correctly.
使用cd命令,导航到Web应用程序的文件夹。 然后输入pm2 start server.js
。 这将使用pm2启动Web应用程序。 然后,键入pm2 save
,它将保存它以便在启动时启动。 如果显示成功保存,则表示已正确保存。
[PM2] Saving current process list...
[PM2] Successfully saved in /root/.pm2/dump.pm2
Finally, type sudo systemctl start pm2-(username)
.
最后,键入sudo systemctl start pm2-(username)
。
Try restarting your droplet by typing reboot and after a few minutes, go to yourdomain.com
. Your web app should be up and running like normal.
尝试通过键入reboot重新启动您的Droplet,几分钟后,请访问yourdomain.com
。 您的网络应用应正常运行。
If you're looking to build on the skills you’ve learned in this tutorial, I suggest using EJS templating to work with APIs and databases.
如果您希望在本教程中学习到的技能基础上,建议您使用EJS模板来使用API和数据库 。
翻译自: https://www.freecodecamp.org/news/develop-deploy-first-fullstack-web-app/
node.js 静态属性