This time I will bring you an analysis of https usage cases in Node.js, what are the precautions for using https in Node.js, the following is a practical case, let’s take a look one time.
ModuleOverview
The importance of this module basically does not need to be emphasized. Today, when network security issues are becoming increasingly serious, it is an inevitable trend for websites to adopt HTTPS. In nodejs, the https module is provided to complete HTTPS related functions. Judging from the official documentation, it is very similar to the usage of the http module.
This article mainly contains two parts:
- An introductory explanation of the https module through examples of the client and server.
- How to access websites with untrusted security certificates. (Take 12306 as an example)
- Due to limited space, this article cannot explain too much about the HTTPS protocol and related technical systems. If you have any questions, please leave a message to exchange.
Client exampleThe usage is very similar to the http module, except that the requested address is https protocol. The code is as follows:
var https = require('https'); https.get('https://www.baidu.com', function(res){ console.log('status code: ' + res.statusCode); console.log('headers: ' + res.headers); res.on('data', function(data){ process.stdout.write(data); }); }).on('error', function(err){ console.error(err); });
Server exampleTo provide HTTPS services to the outside world, an HTTPS certificate is required. If you already have an HTTPS certificate, you can skip the certificate generation step. If not, you can refer to the following steps
Generate a certificate1. Create a directory to store the certificate.
mkdir cert cd cert
2. Generate private key.
openssl genrsa -out chyingp-key.pem 2048
3. Generate a certificate signing request (csr means Certificate Signing Request).
openssl req -new \ -sha256 -key chyingp-key.key.pem \ -out chyingp-csr.pem \ -subj "/C=CN/ST=Guandong/L=Shenzhen/O=YH Inc/CN=www.chyingp.com"
4. Generate certificate.
openssl x509 \ -req -in chyingp-csr.pem \ -signkey chyingp-key.pem \ -out chyingp-cert.pemHTTPS server
The code is as follows:
var https = require('https'); var fs = require('fs'); var options = { key: fs.readFileSync('./cert/chyingp-key.pem'), // 私钥 cert: fs.readFileSync('./cert/chyingp-cert.pem') // 证书 }; var server = https.createServer(options, function(req, res){ res.end('这是来自HTTPS服务器的返回'); }); server.listen(3000);
Since I do not have the domain name www.chyingp.com, I first configure the local host
127.0.0.1 www.chyingp.comStart the service and visit http://www.chyingp.com:3000 in the browser. Note that the browser will prompt you that the certificate is unreliable, just click Trust and continue visiting.
Advanced example: accessing a website with an untrusted security certificateHere is our favorite 12306 as an example. When we access the 12306 ticket purchase page https://kyfw.12306.cn/otn/regist/init through the browser, chrome will prevent us from accessing it. This is because the certificate of 12306 is issued by itself and chrome cannot confirm it. His safety.
To deal with this situation, the following methods can be used:
- Stop visiting: Fellow villagers who are anxious to grab tickets to go home for the New Year say they cannot accept it.
- Ignore the security warning and continue to visit: In most cases, the browser will allow it, but the security prompt will still be there.
- Import the CA root certificate of 12306: the browser obeys and thinks that access is safe. (Actually, there are still security prompts because the signature algorithm used by 12306 does not have enough security level)
Similarly, You will also encounter the same problem when making requests through node https client. Let's do an experiment, the code is as follows:
var https = require('https'); https.get('https://kyfw.12306.cn/otn/regist/init', function(res){ res.on('data', function(data){ process.stdout.write(data); }); }).on('error', function(err){ console.error(err); });
Run the above code and get the following error message, which means that the security certificate is unreliable and continued access is denied.
{ Error: self signed certificate in certificate chainat Error (native)at TLSSocket.
(_tls_wrap.js:1055:38)
at emitNone (events.js:86:13)
at TLSSocket.emit (events.js:185:7)
at TLSSocket._finishInit (_tls_wrap.js:580:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:412:38) code: 'SELF_SIGNED_CERT_IN_CHAIN' }
ps:个人认为这里的错误提示有点误导人,12306网站的证书并不是自签名的,只是对证书签名的CA是12306自家的,不在可信列表里而已。自签名证书,跟自己CA签名的证书还是不一样的。
类似在浏览器里访问,我们可以采取如下处理:
不建议:忽略安全警告,继续访问;
建议:将12306的CA加入受信列表;
方法1:忽略安全警告,继续访问
非常简单,将 rejectUnauthorized 设置为 false 就行,再次运行代码,就可以愉快的返回页面了。
// 例子:忽略安全警告 var https = require('https'); var fs = require('fs'); var options = { hostname: 'kyfw.12306.cn', path: '/otn/leftTicket/init', rejectUnauthorized: false // 忽略安全警告 }; var req = https.get(options, function(res){ res.pipe(process.stdout); }); req.on('error', function(err){ console.error(err.code); });
方法2:将12306的CA加入受信列表
这里包含3个步骤:
下载 12306 的CA证书
将der格式的CA证书,转成pem格式
修改node https的配置
1、下载 12306 的CA证书
在12306的官网上,提供了CA证书的 下载地址 ,将它保存到本地,命名为 srca.cer。
2、将der格式的CA证书,转成pem格式
https初始化client时,提供了 ca 这个配置项,可以将 12306 的CA证书添加进去。当你访问 12306 的网站时,client就会用ca配置项里的 ca 证书,对当前的证书进行校验,于是就校验通过了。
需要注意的是,ca 配置项只支持 pem 格式,而从12306官网下载的是der格式的。需要转换下格式才能用。关于 pem、der的区别,可参考 这里 。
openssl x509 -in srca.cer -inform der -outform pem -out srca.cer.pem
3、修改node https的配置
修改后的代码如下,现在可以愉快的访问12306了。
// 例子:将12306的CA证书,加入我们的信任列表里 var https = require('https'); var fs = require('fs'); var ca = fs.readFileSync('./srca.cer.pem'); var options = { hostname: 'kyfw.12306.cn', path: '/otn/leftTicket/init', ca: [ ca ] }; var req = https.get(options, function(res){ res.pipe(process.stdout); }); req.on('error', function(err){ console.error(err.code); });
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Analysis of https use cases in Node.js. For more information, please follow other related articles on the PHP Chinese website!

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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.

Notepad++7.3.1
Easy-to-use and free code editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.