search
HomeWeb Front-endJS TutorialBasic tutorial on how to use the Request module in Node.js to handle HTTP protocol requests

Here we introduce a Node.js module - request. With this module, http requests become super simple.

Basic tutorial on how to use the Request module in Node.js to handle HTTP protocol requests

Request is super simple to use and supports https and redirection.

var request = require('request');
request('http://www.google.com', function (error, response, body) {
 if (!error && response.statusCode == 200) {
 console.log(body) // 打印google首页
}
})

Streaming:

Any response can be output to a file stream.

Streaming:

Any response can be output to a file stream.

request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))

In turn, you can also pass the file to a PUT or POST request. If no header is provided, the file extension will be detected and the corresponding content-type will be set in the PUT request.

fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'))
Requests can also be piped to themselves. In this case, the original content-type and content-length will be retained.

request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))
Form:

request supports application /x-www-form-urlencoded and multipart/form-data implement form upload.

x-www-form-urlencoded is very simple:

request.post('http://service.com/upload', {form:{key:'value'}})

or:

request.post('http://service.com/upload').form({key:'value'})

Use multipart/form-data and you don’t have to worry about trivial matters such as setting headers, request will help you solve it.

var r = request.post('http://service.com/upload')
var form = r.form()
form.append('my_field', 'my_value')
form.append('my_buffer', new Buffer([1, 2, 3]))
form.append('my_file', fs.createReadStream(path.join(__dirname, 'doodle.png'))
form.append('remote_file', request('http://google.com/doodle.png'))

HTTP authentication:

request.get('http://some.server.com/').auth('username', 'password', false);

or

request.get('http://some.server.com/', {
 'auth': {
 'user': 'username',
 'pass': 'password',
 'sendImmediately': false
}
});

sendImmediately, default is true, send a basic authentication header. After setting it to false, it will retry when receiving a 401 (the server's 401 response must include the WWW-Authenticate specified authentication method).

Support Digest authentication when sendImmediately is true.

OAuth login:

// Twitter OAuth
var qs = require('querystring')
 , oauth =
 { callback: 'http://mysite.com/callback/'
 , consumer_key: CONSUMER_KEY
 , consumer_secret: CONSUMER_SECRET
}
 , url = 'https://api.twitter.com/oauth/request_token'
;
request.post({url:url, oauth:oauth}, function (e, r, body) {
 // Ideally, you would take the body in the response
 // and construct a URL that a user clicks on (like a sign in button).
 // The verifier is only available in the response after a user has
 // verified with twitter that they are authorizing your app.
 var access_token = qs.parse(body)
 , oauth =
 { consumer_key: CONSUMER_KEY
 , consumer_secret: CONSUMER_SECRET
 , token: access_token.oauth_token
 , verifier: access_token.oauth_verifier
}
 , url = 'https://api.twitter.com/oauth/access_token'
;
 request.post({url:url, oauth:oauth}, function (e, r, body) {
 var perm_token = qs.parse(body)
 , oauth =
 { consumer_key: CONSUMER_KEY
 , consumer_secret: CONSUMER_SECRET
 , token: perm_token.oauth_token
 , token_secret: perm_token.oauth_token_secret
}
 , url = 'https://api.twitter.com/1/users/show.json?'
 , params =
 { screen_name: perm_token.screen_name
 , user_id: perm_token.user_id
}
;
 url += qs.stringify(params)
 request.get({url:url, oauth:oauth, json:true}, function (e, r, user) {
console.log(user)
})
})
})

Customized HTTP header

User-Agent can be set in the options object. In the following example, we call the github API to find out the collection number and derivative number of a certain warehouse. We use a customized User-Agent and https.

var request = require('request');
 
var options = {
 url: 'https://api.github.com/repos/mikeal/request',
 headers: {
 'User-Agent': 'request'
}
};
 
function callback(error, response, body) {
 if (!error && response.statusCode == 200) {
 var info = JSON.parse(body);
 console.log(info.stargazers_count +"Stars");
 console.log(info.forks_count +"Forks");
}
}
 
request(options, callback);

cookies:

By default, cookies are disabled. Set jar to true in defaults or options so that subsequent requests will use cookies.

var request = request.defaults({jar: true})
request('http://www.google.com', function () {
request('http://images.google.com')
})

By creating a new instance of request.jar(), you can use customized cookies instead of requesting the global cookie jar.

var j = request.jar()
var request = request.defaults({jar:j})
request('http://www.google.com', function () {
request('http://images.google.com')
})

or

var j = request.jar()
var cookie = request.cookie('your_cookie_here')
j.setCookie(cookie, uri, function (err, cookie){})
request({url: 'http://www.google.com', jar: j}, function () {
request('http://images.google.com')
})

Note that setCookie requires at least three parameters, the last one is the callback function.

You can use the request pipe method to easily obtain the file stream of the image

var request = require('request'),
fs = require('fs');
 
request('https://www.google.com.hk/images/srpr/logo3w.png').pipe(fs.createWriteStream('doodle.png'));

For more usage methods and instructions, please click here to continue reading: https://github.com/mikeal/request/

Example

Here is a very simple example to grab the hotel query data from Qunar.com (get the price ranking of each room type in the hotel within a certain period of time):

var request = require('request'),
fs = require('fs');
 
 
var reqUrl = 'http://hotel.qunar.com/price/detail.jsp?fromDate=2012-08-18&toDate=2012-08-19&cityurl=shanghai_city&HotelSEQ=shanghai_city_2856&cn=5';
 
request({uri:reqUrl}, function(err, response, body) {
 
//console.log(response.statusCode);
//console.log(response);
 
//如果数据量比较大,就需要对返回的数据根据日期、酒店ID进行存储,如果获取数据进行对比的时候直接读文件
var filePath = __dirname + '/data/data.js';
 
if (fs.exists(filePath)) {
 fs.unlinkSync(filePath);
 
 console.log('Del file ' + filePath);
}
 
fs.writeFile(filePath, body, 'utf8', function(err) {
 if (err) {
 throw err;
 }
 
 console.log('Save ' + filePath + ' ok~');
});
 
console.log('Fetch ' + reqUrl + ' ok~');
});

This example comes from A friend who is in the hotel business wants to know the competitiveness of the prices he offers to customers on his website:

1. If the price provided is too low, you will make less money, so if your price is the lowest , you need to see what the second lowest is, and then decide whether to adjust;

2. If the price provided is too high, then the search ranking results will be relatively low, there will be no customers to book the hotel, and the business will be gone

Because we do a lot of hotel booking business, for example, more than 2,000 hotels, if we rely on manual checking of rankings one by one, it will be more passive, and it will be difficult to expand, so I analyzed his needs and it is feasible and possible. Create a good real-time warning system (of course the data will be automatically refreshed on the page every 5 to 10 minutes). Only in this way can profits be maximized, the work efficiency of the sales and customer departments be improved, and the number of hotel cooperation and the company's personnel expansion be accelerated:

1. Don't make a loss, and do not do loss-making transactions;

2. If you find that the price provided is too high If it is low or too high, you need to support calling the API interface of the platform to directly modify the price;

3. It has the function of automatically generating analysis reports to analyze changes in competitors' price adjustment strategies;

More Requests in Node.js Please pay attention to the PHP Chinese website for related articles on the basic usage tutorial of the module processing HTTP protocol requests!

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
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 jQuery Fun and Games Plugins10 jQuery Fun and Games PluginsMar 08, 2025 am 12:42 AM

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

How do I create and publish my own JavaScript libraries?How do I create and publish my own JavaScript libraries?Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

jQuery Parallax Tutorial - Animated Header BackgroundjQuery Parallax Tutorial - Animated Header BackgroundMar 08, 2025 am 12:39 AM

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

Getting Started With Matter.js: IntroductionGetting Started With Matter.js: IntroductionMar 08, 2025 am 12:53 AM

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a

Auto Refresh Div Content Using jQuery and AJAXAuto Refresh Div Content Using jQuery and AJAXMar 08, 2025 am 12:58 AM

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona

How do I optimize JavaScript code for performance in the browser?How do I optimize JavaScript code for performance in the browser?Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

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

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.