Home > Web Front-end > Front-end Q&A > nodejs initiates https request

nodejs initiates https request

WBOY
Release: 2023-05-23 14:23:07
Original
2703 people have browsed it

Node.js is a popular Javascript running environment that is fast, efficient, and event-driven. In Node.js, HTTP and HTTPS requests can be easily initiated using the built-in http and https modules. This article will introduce how to use Node.js to initiate HTTPS requests.

1. https module in Node.js

In Node.js, you can use the built-in https module to initiate HTTPS requests. The https module provides an interface similar to the http module, which can obtain data from an HTTPS server by sending HTTP requests.

Before using the https module, you need to use the require method to introduce the https module:

const https = require('https');

2. Initiate an HTTPS request

To initiate an HTTPS request, we need to use the https.request(options, callback) function. The options parameter is an object that contains the information needed to initiate a request, such as the requested URL, the requested method, the request header, etc. The callback parameter is a function used to handle the server response. This function has one parameter, which is the server response object.

The following is the basic model for initiating HTTPS requests:

const https = require('https');

const options = {
  // 请求的URL
  hostname: 'example.com',

  // 请求的方法,默认是GET
  method: 'GET',

  // 请求的头信息
  headers: {
    'Content-Type': 'application/json'
  }
};

const req = https.request(options, res => {
  console.log(`状态码: ${res.statusCode}`);

  res.on('data', d => {
    process.stdout.write(d);
  });
});

req.on('error', error => {
  console.error(error);
});

req.end();
Copy after login

In this example, we use the https.request(options, callback) function to initiate an HTTPS request. We set the requested URL to example.com, the request method to GET, and the Content-Type in the request header to application/json.

After the server responds, we process the server response through the callback function. We will first output the status code of the server, and then use the process.stdout.write method to output the data to the console when receiving data.

3. Options parameters of HTTPS requests

In the previous section, we mentioned that the options parameters are required to initiate HTTPS requests. The options parameter is an object containing request information. The most basic attributes are:

  • hostname: the requested host name
  • port: the requested port number, generally HTTPS protocol The port number is 443
  • path: the path of the request, that is, the location of the requested resource in the server, such as /albums
  • method: the request method, commonly used ones are GET and POST
  • headers: Request headers, including some client information, such as Accept, User-Agent, Content-Type, etc.

The following is an example of a complete options parameter:

const options = {
  hostname: 'example.com',
  port: 443,
  path: '/albums',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length,
    'User-Agent': 'Mozilla/5.0'
  }
};
Copy after login

This options object represents a POST request to port 443 of example.com. The request path is /albums. The request header contains three attributes: Content-Type, Content-Length and User-Agent.

4. Processing HTTPS response

When an HTTPS request is initiated, the server will return a response object, through which we can obtain the server's response. The response object is a readable stream. We can use the on() method to listen to the data and end events to obtain the data returned by the server.

The following is an example of processing an HTTPS response:

const req = https.request(options, res => {
  let data = '';

  console.log(`状态码: ${res.statusCode}`);

  res.on('data', chunk => {
    data += chunk;
  });

  res.on('end', () => {
    console.log('响应数据: ');
    console.log(data);
  });
});

req.on('error', error => {
  console.error(`请求发生错误:${error}`);
});

req.end();
Copy after login

In this example, we determine whether the request is successful based on the status code (statusCode) of the HTTP response. In the data receiving callback function, we use the = operator to concatenate each data chunk into a complete response data. When all data is received, we use console.log to output the complete response data.

5. Encrypted HTTPS request

HTTPS is a secure HTTP protocol based on the TLS/SSL protocol. It uses public key encryption and private key decryption to protect data security. In Node.js, using the https module to initiate an HTTPS request is using the secure HTTPS protocol.

If the server uses a self-signed certificate, then we need to set the rejectUnauthorized attribute to false in the options object, as shown below:

const options = {
  hostname: 'example.com',
  port: 443,
  path: '/albums',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length,
    'User-Agent': 'Mozilla/5.0'
  },
  rejectUnauthorized: false
};
Copy after login

As you can see, we added rejectUnauthorized in the options object : false attribute. This option is used to accept unsigned certificates. If not set, an error will be reported when the server uses unsigned certificates.

6. Summary

This article introduces how to use the built-in https module in Node.js to initiate HTTPS requests. We make requests through the https.request(options, callback) function, use the options parameters to set the request information, and use the callback parameters to process the server response. At the same time, we introduced how to ensure data encryption security when processing HTTPS requests.

The built-in https module of Node.js provides a convenient way to initiate HTTPS requests. It can easily obtain or submit data during development, allowing us to develop applications more efficiently.

The above is the detailed content of nodejs initiates https request. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template