search
HomeWeb Front-endFront-end Q&Anodejs request address

In the process of web development, we often need to send requests to the backend, obtain data or perform some operations. Node.js provides a quick and easy way to send requests and process the returned content. This article will introduce how to use Node.js to send HTTP/HTTPS requests and process the returned request content.

First, we need to install the request package, which is a popular way to send HTTP requests in Node.js. You can install it with the following command:

npm install request

After the installation is complete, you can use the request package to send HTTP/HTTPS requests.

Send a request

Using requestSending a request is very simple. You only need to pass in a URL parameter, for example:

const request = require('request');

request('https://www.baidu.com', function (error, response, body) {
  console.log('error:', error); // 打印错误信息
  console.log('statusCode:', response && response.statusCode); // 打印响应状态码
  console.log('body:', body); // 打印HTML内容
});

The above code sends a GET request to Baidu website and print the response status code and HTML content.

If you need to send a POST request, you need to pass in an entity containing the request parameters:

const request = require('request');

request.post('https://api.example.com/login', {form: {username: 'example', password: 'password'}}, 
  function (error, response, body) {
    console.log('error:', error); // 打印错误信息
    console.log('statusCode:', response && response.statusCode); // 打印响应状态码
    console.log('body:', body); // 打印响应内容
  }
);

The above code sends a POST request to https://api.example.com/ login, with username and password parameters. form is a parameter entity that contains the requested parameters.

Processing the response

When the request is executed, request will return a response object after the callback, which contains the status code and entity content of the response. You can use response.statusCode to access the response status code and response.body to access the entity content.

In addition to printing the content directly, the returned content can also be parsed and processed. Common processing methods include string parsing, JSON parsing, binary parsing, etc.

For example, when the callback returns HTML content, you can use cheerio or node-html-parser to parse:

const request = require('request');
const cheerio = require('cheerio');

request('https://www.example.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    const $ = cheerio.load(body);
    console.log($('title').text());
  }
});

The above code uses cheerio parses the HTML content and prints the title of the web page.

When the callback returns content in JSON format, you can use the JSON.parse method to parse the JSON string. For example:

const request = require('request');

request('https://api.example.com/users/1', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    const user = JSON.parse(body);
    console.log(user.name);
    console.log(user.email);
  }
});

The above code parses the returned JSON content and prints the user's name and email.

When the callback returns binary content, you can use the Buffer object for decoding. For example:

const request = require('request');

request('https://www.example.com/logo.png', {encoding: null}, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    const data = 'data:' + response.headers['content-type'] + ';base64,' + Buffer.from(body).toString('base64');
    console.log(data);
  }
});

The above code obtains a PNG image and uses the Buffer object to decode the returned binary data.

Send HTTPS request

If you need to send HTTPS request, you need to use the https package. The https package is a package that comes with Node.js and does not need to be installed. You can send an HTTPS request like the following code:

const https = require('https');

https.get('https://www.example.com', function (response) {
  console.log('statusCode:', response.statusCode);
  console.log('headers:', response.headers);

  response.on('data', function (data) {
    console.log(data.toString());
  });
});

The above code uses the https.get method to send an HTTPS GET request and prints the response status code and response header. Use the response.on method to listen to the stream of returned content and process it.

HTTPS requests require security authentication, so an HTTPS certificate is required. You can add ca, cert, key and other attributes to the parameters to specify the certificate.

For example:

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

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

https.get('https://www.example.com', options, function (response) {
  console.log('statusCode:', response.statusCode);
  console.log('headers:', response.headers);

  response.on('data', function (data) {
    console.log(data.toString());
  });
});

The above code uses its own certificate, where ca is the certificate chain of the root certificate, cert and key is your own certificate and private key.

Summary

This article introduces how to send HTTP/HTTPS requests in Node.js and how to process the returned content. Finally, it should be noted that sending HTTP requests may involve cross-domain issues, and cross-domain request headers need to be set. At the same time, you also need to pay attention to security issues and performance issues to avoid making too many requests or leaking sensitive information.

The above is the detailed content of nodejs request address. 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
CSS: Is it bad to use ID selector?CSS: Is it bad to use ID selector?May 13, 2025 am 12:14 AM

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5: Goals in 2024HTML5: Goals in 2024May 13, 2025 am 12:13 AM

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

What are the main areas where HTML5 tried to improve?What are the main areas where HTML5 tried to improve?May 13, 2025 am 12:12 AM

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

CSS ID and Class: common mistakesCSS ID and Class: common mistakesMay 13, 2025 am 12:11 AM

IDsshouldbeusedforJavaScripthooks,whileclassesarebetterforstyling.1)Useclassesforstylingtoallowforeasierreuseandavoidspecificityissues.2)UseIDsforJavaScripthookstouniquelyidentifyelements.3)Avoiddeepnestingtokeepselectorssimpleandimproveperformance.4

What is thedifference between class and id selector?What is thedifference between class and id selector?May 12, 2025 am 12:13 AM

Classselectorsareversatileandreusable,whileidselectorsareuniqueandspecific.1)Useclassselectors(denotedby.)forstylingmultipleelementswithsharedcharacteristics.2)Useidselectors(denotedby#)forstylinguniqueelementsonapage.Classselectorsoffermoreflexibili

CSS IDs vs Classes: The real differencesCSS IDs vs Classes: The real differencesMay 12, 2025 am 12:10 AM

IDsareuniqueidentifiersforsingleelements,whileclassesstylemultipleelements.1)UseIDsforuniqueelementsandJavaScripthooks.2)Useclassesforreusable,flexiblestylingacrossmultipleelements.

CSS: What if I use just classes?CSS: What if I use just classes?May 12, 2025 am 12:09 AM

Using a class-only selector can improve code reusability and maintainability, but requires managing class names and priorities. 1. Improve reusability and flexibility, 2. Combining multiple classes to create complex styles, 3. It may lead to lengthy class names and priorities, 4. The performance impact is small, 5. Follow best practices such as concise naming and usage conventions.

ID and Class Selectors in CSS: A Beginner's GuideID and Class Selectors in CSS: A Beginner's GuideMay 12, 2025 am 12:06 AM

ID and class selectors are used in CSS for unique and multi-element style settings respectively. 1. The ID selector (#) is suitable for a single element, such as a specific navigation menu. 2.Class selector (.) is used for multiple elements, such as unified button style. IDs should be used with caution, avoid excessive specificity, and prioritize class for improved style reusability and flexibility.

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

Safe Exam Browser

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.