Table of Contents
Send a request
Processing the response
Send HTTPS request
Summary
Home Web Front-end Front-end Q&A nodejs request address

nodejs request address

May 13, 2023 pm 09:29 PM

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
Copy after login

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内容
});
Copy after login

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); // 打印响应内容
  }
);
Copy after login

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());
  }
});
Copy after login

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);
  }
});
Copy after login

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);
  }
});
Copy after login

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());
  });
});
Copy after login

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());
  });
});
Copy after login

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 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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is useEffect? How do you use it to perform side effects? What is useEffect? How do you use it to perform side effects? Mar 19, 2025 pm 03:58 PM

The article discusses useEffect in React, a hook for managing side effects like data fetching and DOM manipulation in functional components. It explains usage, common side effects, and cleanup to prevent issues like memory leaks.

Explain the concept of lazy loading. Explain the concept of lazy loading. Mar 13, 2025 pm 07:47 PM

Lazy loading delays loading of content until needed, improving web performance and user experience by reducing initial load times and server load.

What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code? What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code? Mar 18, 2025 pm 01:44 PM

Higher-order functions in JavaScript enhance code conciseness, reusability, modularity, and performance through abstraction, common patterns, and optimization techniques.

How does currying work in JavaScript, and what are its benefits? How does currying work in JavaScript, and what are its benefits? Mar 18, 2025 pm 01:45 PM

The article discusses currying in JavaScript, a technique transforming multi-argument functions into single-argument function sequences. It explores currying's implementation, benefits like partial application, and practical uses, enhancing code read

How does the React reconciliation algorithm work? How does the React reconciliation algorithm work? Mar 18, 2025 pm 01:58 PM

The article explains React's reconciliation algorithm, which efficiently updates the DOM by comparing Virtual DOM trees. It discusses performance benefits, optimization techniques, and impacts on user experience.Character count: 159

What is useContext? How do you use it to share state between components? What is useContext? How do you use it to share state between components? Mar 19, 2025 pm 03:59 PM

The article explains useContext in React, which simplifies state management by avoiding prop drilling. It discusses benefits like centralized state and performance improvements through reduced re-renders.

How do you prevent default behavior in event handlers? How do you prevent default behavior in event handlers? Mar 19, 2025 pm 04:10 PM

Article discusses preventing default behavior in event handlers using preventDefault() method, its benefits like enhanced user experience, and potential issues like accessibility concerns.

What are the advantages and disadvantages of controlled and uncontrolled components? What are the advantages and disadvantages of controlled and uncontrolled components? Mar 19, 2025 pm 04:16 PM

The article discusses the advantages and disadvantages of controlled and uncontrolled components in React, focusing on aspects like predictability, performance, and use cases. It advises on factors to consider when choosing between them.

See all articles