Hướng dẫn https nodejs - https nodejs

Node.js là môi trường máy chủ mã nguồn mở miễn phí chạy trên nhiều hệ điều hành khác nhau như Windows, Linux, Unix, Mac, OS X, v.v. Node.js đang sử dụng các tập lệnh Java cho chức năng trên máy chủ.

Quá trình cài đặt chứng chỉ SSL trên Node.js khá đơn giản. Quá trình này có thể được chia thành ba bước.

Hướng dẫn https nodejs - https nodejs

Thực hiện các bước sau để cài đặt chứng chỉ SSL nhanh trên node.js.

Bước 1: Tải chứng chỉ SSL

Đăng nhập vào trang quản lý chứng chỉ tại https://muassl.com, chọn Lấy SSL và tải về các chứng chỉ tương ứng.

Bước 2: Tạo file https_server.js & tải lên các chứng chỉ SSL trên máy chủ

Để tạo file https_server.js , sử dụng các thông số như bên dưới. bạn có thể sử dụng tên khác thay cho tên Server.js .

#vim https_server.js
var https = require('https');
var fs = require('fs');
var https_options = {
  key: fs.readFileSync("/path/to/private.key"),
  cert: fs.readFileSync("/path/to/your_domain_name.crt"),
  ca: [
          fs.readFileSync('path/to/CA_root.crt'),
          fs.readFileSync('path/to/ca_bundle_certificate.crt')
       ]
};
https.createServer(options, function (req, res) {
 res.writeHead(200);
 res.end("Welcome to Node.js HTTPS Servern");
}).listen(8443)

Ghi chú:

path/to/private.key – đường dẫn đầy đủ dẫn đến Khóa riêng.

path/to/your_domain_name.crt – đường dẫn đầy đủ dẫn đến file chứng chỉ SSL

path/to/CA_root.crt’ – đường dẫn đầy đủ đến file Root.

path/to/ca_bundle_certificate – đường dẫn đầy đủ đến CA Bundle

Bước 3: Khởi động Node.js

Áp dụng dòng lệnh sau để khởi động ứng dụng Node.js mà bạn đã tạo ở trên.

# node https_server.js

To create an HTTPS server, you need two things: an SSL certificate, and built-in

var https = require('https');
var fs = require('fs');
var https_options = {
  key: fs.readFileSync("/path/to/private.key"),
  cert: fs.readFileSync("/path/to/your_domain_name.crt"),
  ca: [
          fs.readFileSync('path/to/CA_root.crt'),
          fs.readFileSync('path/to/ca_bundle_certificate.crt')
       ]
};
0 Node.js module.

We need to start out with a word about SSL certificates. Speaking generally, there are two kinds of certificates: those signed by a 'Certificate Authority', or CA, and 'self-signed certificates'. A Certificate Authority is a trusted source for an SSL certificate, and using a certificate from a CA allows your users to trust the identity of your website. In most cases, you would want to use a CA-signed certificate in a production environment - for testing purposes, however, a self-signed certificate will do just fine.

To generate a self-signed certificate, run the following in your shell:

openssl genrsa -out key.pem
openssl req -new -key key.pem -out csr.pem
openssl x509 -req -days 9999 -in csr.pem -signkey key.pem -out cert.pem
rm csr.pem

This should leave you with two files,

var https = require('https');
var fs = require('fs');
var https_options = {
  key: fs.readFileSync("/path/to/private.key"),
  cert: fs.readFileSync("/path/to/your_domain_name.crt"),
  ca: [
          fs.readFileSync('path/to/CA_root.crt'),
          fs.readFileSync('path/to/ca_bundle_certificate.crt')
       ]
};
1 (the certificate) and
var https = require('https');
var fs = require('fs');
var https_options = {
  key: fs.readFileSync("/path/to/private.key"),
  cert: fs.readFileSync("/path/to/your_domain_name.crt"),
  ca: [
          fs.readFileSync('path/to/CA_root.crt'),
          fs.readFileSync('path/to/ca_bundle_certificate.crt')
       ]
};
2 (the private key). Put these files in the same directory as your Node.js server file. This is all you need for a SSL connection. So now you set up a quick hello world example (the biggest difference between https and http is the
var https = require('https');
var fs = require('fs');
var https_options = {
  key: fs.readFileSync("/path/to/private.key"),
  cert: fs.readFileSync("/path/to/your_domain_name.crt"),
  ca: [
          fs.readFileSync('path/to/CA_root.crt'),
          fs.readFileSync('path/to/ca_bundle_certificate.crt')
       ]
};
3 parameter):

const https = require('https');
const fs = require('fs');

const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

https.createServer(options, function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}).listen(8000);

NODE PRO TIP: Note

var https = require('https');
var fs = require('fs');
var https_options = {
  key: fs.readFileSync("/path/to/private.key"),
  cert: fs.readFileSync("/path/to/your_domain_name.crt"),
  ca: [
          fs.readFileSync('path/to/CA_root.crt'),
          fs.readFileSync('path/to/ca_bundle_certificate.crt')
       ]
};
4 - unlike
var https = require('https');
var fs = require('fs');
var https_options = {
  key: fs.readFileSync("/path/to/private.key"),
  cert: fs.readFileSync("/path/to/your_domain_name.crt"),
  ca: [
          fs.readFileSync('path/to/CA_root.crt'),
          fs.readFileSync('path/to/ca_bundle_certificate.crt')
       ]
};
5,
var https = require('https');
var fs = require('fs');
var https_options = {
  key: fs.readFileSync("/path/to/private.key"),
  cert: fs.readFileSync("/path/to/your_domain_name.crt"),
  ca: [
          fs.readFileSync('path/to/CA_root.crt'),
          fs.readFileSync('path/to/ca_bundle_certificate.crt')
       ]
};
4 will block the entire process until it completes. In situations like this - loading vital configuration data - the
var https = require('https');
var fs = require('fs');
var https_options = {
  key: fs.readFileSync("/path/to/private.key"),
  cert: fs.readFileSync("/path/to/your_domain_name.crt"),
  ca: [
          fs.readFileSync('path/to/CA_root.crt'),
          fs.readFileSync('path/to/ca_bundle_certificate.crt')
       ]
};
7 functions are okay. In a busy server, however, using a synchronous function during a request will force the server to deal with the requests one by one!

To start your https server, run

var https = require('https');
var fs = require('fs');
var https_options = {
  key: fs.readFileSync("/path/to/private.key"),
  cert: fs.readFileSync("/path/to/your_domain_name.crt"),
  ca: [
          fs.readFileSync('path/to/CA_root.crt'),
          fs.readFileSync('path/to/ca_bundle_certificate.crt')
       ]
};
8 (here, app.js is name of the file) on the terminal.

Now that your server is set up and started, you should be able to get the file with curl:

curl -k https://localhost:8000

or in your browser, by going to https://localhost:8000 .

Nội dung bài viết

Video học lập trình mỗi ngày

Việc đầu tiên đương nhiên các bạn phải biết install node và biết khi nào chúng ta nên sử dụng Nodejs. Và cũng tất nhiên bạn nên tìm hiểu xem Http Request là gì? trước khi đọc bài này.

Request nodejs with https

Đầu tiên trong bài viết này là module HTTP mặc định trong thư viện chuẩn. Với module này, bạn chỉ cần sử dụng mà không phụ thuốc các install bên ngoài. Tất nhiên nó là dạng chuẩn nên không chuẩn so với các giải pháp mà chuẩn bị chúng ta liệt kê dưới đây. https là gì?Ví dụ về http:
Ví dụ về http:

const https = require('https');
https.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', (resp) => {
  let data = '';
  // A chunk of data has been recieved.
  resp.on('data', (chunk) => {
    data += chunk;
  });
  // The whole response has been received. Print out the result.
  resp.on('end', () => {
    console.log(JSON.parse(data).explanation);
  });
}).on("error", (err) => {
  console.log("Error: " + err.message);
});

Request là một ứng dụng HTTP được đơn giản hóa có thể so sánh được với thư viện yêu cầu của Python. Thư viện này thân thiện hơn nhiều so với module http mặc định và đã được coi là một sự truy cập cho cộng đồng trong nhiều năm.  Đây là lựa chọn của nhiều người trong đó có tôi kể từ khi tôi bắt đầu sử dụng Node.js và rất tuyệt vời để nhanh chóng hoàn thành công việc. Không giống như module http, bạn sẽ phải cài đặt module này làm phụ thuộc từ npm, nghĩa là bạn phải install nó.

Ví dụ về Request:

npm install  //install in node use npm
const request = require('request');
request('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', { json: true }, (err, res, body) => {
  if (err) { return console.log(err); }
  console.log(body.url);
  console.log(body.explanation);
});


Use Axios in Nodejs

Axios là một based HTTP client dựa trên promise cho trình duyệt cũng như node.js. Sử dụng Promises là một lợi thế lớn khi giao dịch với mã đòi hỏi một chuỗi sự kiện phức tạp hơn. Viết mã không đồng bộ có thể gây nhầm lẫn và Promises là một trong nhiều giải pháp cho vấn đề này. Ngoài ra chúng thậm chí còn hữu ích trong các ngôn ngữ khác như Swift.Ví dụ về Axios:
Ví dụ về Axios:

const axios = require('axios');
axios.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY')
  .then(response => {
    console.log(response.data.url);
    console.log(response.data.explanation);
  })
  .catch(error => {
    console.log(error);
  });

Kết Luận


Đương nhiên tất cả các cách trên không bao gồm tất cả các giải pháp, nhưng bây giờ bạn thấy cách chức năng cơ bản hoạt động trong một vài thư viện HTTP phổ biến nhất trong Node. Ngoài ra còn có các thư viện như  fetch để chuyển các chức năng tìm nạp của trình duyệt sang chương trình phụ trợ. Các ngôn ngữ khác có nhiều thư viện tương tự để giải quyết vấn đề này. Xem các hướng dẫn khác trong Swift, Python và Ruby. Ngoài ra, hãy xem Quickstarts của Node.js của chúng tôi để có nơi áp dụng các kỹ năng mới của bạn. Hy vọng bài viết này sẽ cung cấp cho các bạn thêm phần lựa chọn trong các thực hiện của các bạn.Các bạn có thể tham khảo thêm ở đây : Ref Document fetch để chuyển các chức năng tìm nạp của trình duyệt sang chương trình phụ trợ. Các ngôn ngữ khác có nhiều thư viện tương tự để giải quyết vấn đề này. Xem các hướng dẫn khác trong Swift, Python và Ruby. Ngoài ra, hãy xem Quickstarts của Node.js của chúng tôi để có nơi áp dụng các kỹ năng mới của bạn. Hy vọng bài viết này sẽ cung cấp cho các bạn thêm phần lựa chọn trong các thực hiện của các bạn.
Các bạn có thể tham khảo thêm ở đây : Ref Document