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 request
Sending 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!

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'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

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

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

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

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

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


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

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
A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

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.
