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

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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.

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

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

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

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

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.

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

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.
