search
HomeWeb Front-endJS TutorialHow to deploy HTTPS in Node.js

How to deploy HTTPS in Node.js

Mar 19, 2018 pm 05:04 PM
httpsjavascriptnode.js

This time I will show you how to deploy HTTPS in Node.js. What are the precautions for deploying HTTPS in Node.js? The following is a practical case, let's take a look.

With the rapid development of the Internet, Internet information security has attracted more and more attention.

HTTPS should be one of the technologies that major manufacturers have been trying to popularize in the past two years. Major domestic manufacturers have basically fully popularized HTTPS.

HTTPS Current Situation

This article will introduce to you

Node.js How to deploy free HTTPS and simple deploymentHTTP/ 2.

As of March 13, 2018, real-time statistical reports from Let's Encrypt show that among the more than 69.3 million active websites counted, 53.5 million (about 77%) have deployed

HTTPS Certificate Services.

lets encrypt stats

At the same time, the Google Transparency Report - HTTPS encryption on the network, statistics on the growth of HTTPS usage in the statistics of sites visited using the Chrome browser:

google stats

In February this year, the Chrome team also announced that in Chrome 68, released in July 2018, websites that do not deploy HTTPS will be marked as "unsafe".

chrome 68 status

In short, HTTPS is the way to go.

Node.js Deploying HTTPS

As early as in the article "From HTTP to HTTPS - IIS Deploying Free HTTPS", I pointed out the advantages of Let's Encrypt free certificate:

Services provided by ISRG (Internet Security Research Group, Internet Security Research Group), free, fast access, stable, etc.

So the certificate deployed this time also revolves around

Let's Encrypt.

greenlock-express

Due to the prosperity of the js ecosystem, it is very easy to find an existing package. The greenlock-express package helps us encapsulate it

To deploy Let's Enctrypt certificate, you only need to introduce this package and use it:

  1. Automatic registration

    Let's Encrypt Certificate

  2. Automatic renewal (about 80 days), and the server does not need to be restarted

  3. Supports

    Virtual host

  4. # #And
greenlock

The related certificate ecosystem is very complete, and there is also greenlock-koa that supports koa. Installation and use

Install via

npm

greenlock-express:<pre class="brush:php;toolbar:false">$ npm install --save greenlock-express@2.x</pre>It’s very simple to use, it’s

greenlock-express

The demo provided by default: <pre class="brush:php;toolbar:false">const greenlock = require('greenlock-express') require('greenlock-express').create({   // 测试   server: 'staging',   // 联系邮箱   email: 'john.doe@example.com',   // 是否同意 Let's Encrypt 条款... 这必须为 true 啊,不然走不下去   agreeTos: true,   // 申请的域名列表,不支持通配符   approveDomains: [ 'tasaid.com', 'www.tasaid.com' ],   // 绑定 express app   app: require('express')().use('/', function (req, res) {     res.end('Hello, World!');   }) }).listen(80, 443)</pre>The certificate exists

~/letsencrypt

. Of course the above code can only be used in the test/development environment, because it does not apply for a valid certificate, but generates a self-signed certificate (the same as the previous 12306 self-signed certificate), which is used Debugging in a development environment.

API

greenlock-express

’s create(options) Function parameters are signed as follows:

interface Options {
  /**
   * Express app
   */
  app: Express
  /*
   * 远程服务器
   * 测试环境中可用为 staging
   * 生产环境中为 https://acme-v01.api.letsencrypt.org/directory
   */
  server: string
  /**
   * 用于接收 let's encrypt 协议的邮箱
   */
  email: string
  /**
   * 是否同意协议
   */
  agreeTos: boolean
  /**
   * 在注册域名获取证书前,会执行这个回调函数
   * string[]: 一组需要注册证书的域名
   * 函数: 第一个参数跟 Options 格式差不多,第二个参数是当前自动获取的域名信息,第三个参数是在处理完之后传递的回调函数
   */
  approveDomains: string[] | (opts, certs: cb) => any
  /**
   * 更新证书最大天数 (以毫秒为单位)
   */
  renewWithin: number
  /**
   * 更新证书的最小天数(以毫秒为单位)
   */
  renewBy: number
}
After testing, in a real production environment,

approveDomains

must be a function, and passing an array will not take effect. Production environment

Deployment in the production environment also requires some configuration changes and the introduction of some packages.

Update package:

$ npm i --save greenlock-express@2.x
$ npm i --save le-challenge-fs
$ npm i --save le-store-certbot
$ npm i --save redirect-https

Production code:

const greenlock = require('greenlock-express')
const express = require('express')
const app = express()
const lex = greenlock.create({
  // 注意这里要成这个固定地址
  server: 'https://acme-v01.api.letsencrypt.org/directory',
  challenges: { 
    'http-01': require('le-challenge-fs').create({ webrootPath: '~/letsencrypt/var/acme-challenges' }) 
  },
  store: require('le-store-certbot').create({ 
    webrootPath: '~/letsencrypt/srv/www/:hostname/.well-known/acme-challenge' 
  }),
  approveDomains: (opts: any, certs: any, cb: any) => {
    appLog.info('approveDomains', { opts, certs })
    if (certs) {
      /*
       * 注意这里如果是这样写的话,一定要对域名做校验
       * 否则其他人可以通过将域名指向你的服务器地址,导致你注册了其他域名的证书
       * 从而造成安全性问题
       */
      // opts.domains = certs.altnames
      opts.domains = [ 'tasaid.com', 'www.tasaid.com' ]
    } else {
      opts.email = '你的邮箱@live.com'
      opts.agreeTos = true
    }
    cb(null, { options: opts, certs: certs })
  },
})
// 这里的 redirect-https 用于自动将 HTTP 请求跳到 HTTPS 上
require('http').createServer(
  lex.middleware(
    require('redirect-https')()
   )
  ).listen(80, function () {
    console.log('Listening', `for ACME http-01 challenges on: ${JSON.stringify(this.address())}`)
})
// 绑定 HTTPS 端口
require('https').createServer(
    lex.httpsOptions, 
    lex.middleware(app)
  ).listen(443, function () {
    console.log(('App is running at http://localhost:%d in %s mode'), app.get('port'), app.get('env'))
    console.log('Press CTRL-C to stop\n')
})

If it does not take effect, you can check the certificate information of

~/letsencrypt

and whether port 443 is correct Open. Deploying HTTP/2

HTTP/2 is an upgraded version of HTTP/1.1, which mainly improves the following aspects:

    Binary protocol: Using binary streams
  1. Multiplexing: Multiplexing pipelines for one request
  2. 服务器推送:解决 HTTP/1.x 时代最大的痛点

值的注意的是,HTTP/2 是支持 HTTP 协议的,只不过浏览器厂商都不愿意支持 HTTP,所以基本上可以认为,用上 HTTP/2 的前置条件是必须部署 HTTPS。

SPDY

早在 2009 年,Google 开发了一个实验性协议,叫做 SPDY,目的解决 HTTP/1.x 中的一些设计缺陷。在 SPDY 发布几年后,这个新的实验性协议得到了 Chrome、Firefox 和 Opera 的支持,应用越来越广泛。然后 HTTP 工作组 (HTTP-WG) 在这个 SPDY 的基础上,设计了 HTTP/2,所以可以说 SPDY 是 HTTP/2 的前身。

关于 HTTP/2 的详情可以参考 这篇文章。

部署 HTTP/2

引入 HTTP/2Node.js 中也十分简单,只需要引入 spdy 包即可:

$ npm i --save spdy

然后我们把上一节的代码做一点修改即可支持 HTTP/2:

const greenlock = require('greenlock-express')
const express = require('express')
// HTTP/2
const spdy = require('spdy')
const app = express()
const lex = greenlock.create({
  // 注意这里要成这个固定地址
  server: 'https://acme-v01.api.letsencrypt.org/directory',
  challenges: { 
    'http-01': require('le-challenge-fs').create({ webrootPath: '~/letsencrypt/var/acme-challenges' }) 
  },
  store: require('le-store-certbot').create({ 
    webrootPath: '~/letsencrypt/srv/www/:hostname/.well-known/acme-challenge' 
  }),
  approveDomains: (opts: any, certs: any, cb: any) => {
    appLog.info('approveDomains', { opts, certs })
    if (certs) {
      /*
       * 注意这里如果是这样写的话,一定要对域名做校验
       * 否则其他人可以通过将域名指向你的服务器地址,导致你注册了其他域名的证书
       * 从而造成安全性问题
       */
      // opts.domains = certs.altnames
      opts.domains = [ 'tasaid.com', 'www.tasaid.com' ]
    } else {
      opts.email = '你的邮箱@live.com'
      opts.agreeTos = true
    }
    cb(null, { options: opts, certs: certs })
  },
})
// 这里的 redirect-https 用于自动将 HTTP 请求跳到 HTTPS 上
require('http').createServer(
  lex.middleware(
    require('redirect-https')()
   )
  ).listen(80, function () {
    console.log('Listening', `for ACME http-01 challenges on: ${JSON.stringify(this.address())}`)
})
// HTTP/2
spdy.createServer(lex.httpsOptions, lex.middleware(app)).listen(443, function () {
  console.log('Listening https', `for ACME tls-sni-01 challenges and serve app on: ${JSON.stringify(this.address())}`)
})

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

正则表达式怎么在字符串中提取数字

React中有哪些类定义组件

The above is the detailed content of How to deploy HTTPS in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor