


Introduction to the use of the Request module in Node.js to handle HTTP protocol requests
This article mainly introduces the basic usage tutorial of the Request module in Node.js to handle HTTP requests. request also supports OAuth signature requests, which is very good and powerful. Friends who need it can refer to it
Here Introducing a Node.js module - request. With this module, http requests become super simple.
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首页 } })
Stream:
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 to implement form upload.
x-www-form-urlencoded is simple:
request.post('http://service.com/upload', {form:{key:'value'}})
or:
request.post('http://service.com/upload').form({key:'value'})
When using multipart/form-data, 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, defaults to true, sends 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).
Digest authentication is supported 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 and the like can be found in 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 Customize 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 pipe method of request 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, click here to continue reading :https://github.com/mikeal/request/
Example
A very simple example is written here to grab hotels from Qunar.com Query data (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 and wants to know what he provides to customers on the website Price competitiveness:
1. If the price offered 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, the ranking results will be relatively low. There will be no customers to book the hotel, and the business will be gone.
Because the hotel is made There are many booking businesses, for example, more than 2,000. If you rely on manual checking of rankings one by one, it will be passive, and it will be difficult to expand. Therefore, I analyzed his needs and it is feasible and can be made into a good one. 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 cooperations and the company's personnel expansion be accelerated:
1. Do not lose money and do not do loss-making transactions;
2. If you find that the price provided is too low or too high, you need to support calling the API interface of the platform to directly modify the price;
3. There is a function to automatically generate analysis reports to analyze competitors' price adjustment strategies. Changes;
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
Introduction to module definition in nodejs
Learning about the cluster module in Node
nodejs method to implement bigpipe asynchronous loading of pages
The above is the detailed content of Introduction to the use of the Request module in Node.js to handle HTTP protocol requests. 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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.
