- Mastering Node.js(Second Edition)
- Sandro Pasquali Kevin Faaborg
- 157字
- 2021-07-02 19:28:49
Making HTTP requests
It is often necessary for a network application to make external HTTP calls. HTTP servers are also often called upon to perform HTTP services for clients making requests. Node provides an easy interface for making external HTTP calls.
For example, the following code will fetch the HTML front page of www.example.org:
const http = require('http');
http.request({
host: 'www.example.org',
method: 'GET',
path: "/"
}, function(response) {
response.setEncoding("utf8");
response.on("readable", () => console.log(response.read()));
}).end();
As we can see, we are working with a Readable stream, which can be written to a file.
A popular Node module for managing HTTP requests is Mikeal Roger's request: https://github.com/request/request
Because it is common to use HTTP.request in order to GET external pages, Node offers a shortcut:
http.get("http://www.example.org/", response => {
console.log(`Status: ${response.statusCode}`);
}).on('error', err => {
console.log("Error: " + err.message);
});
Let's now look at some more advanced implementations of HTTP servers, where we perform general network services for clients.
推薦閱讀
- 微商之道
- Hands-On Chatbots and Conversational UI Development
- 網(wǎng)絡(luò)互聯(lián)技術(shù)(實(shí)踐篇)
- Practical Web Design
- NB-IoT物聯(lián)網(wǎng)技術(shù)解析與案例詳解
- 企業(yè)網(wǎng)絡(luò)安全管理
- 端到端QoS網(wǎng)絡(luò)設(shè)計(jì)
- 從實(shí)踐中學(xué)習(xí)手機(jī)抓包與數(shù)據(jù)分析
- Hands-On Microservices with Node.js
- Microsoft Power Platform Enterprise Architecture
- 大型企業(yè)微服務(wù)架構(gòu)實(shí)踐與運(yùn)營
- 一本書讀懂物聯(lián)網(wǎng)
- 現(xiàn)代通信系統(tǒng)(第5版)
- 一本書讀懂TCP/IP
- 5G非正交多址接入技術(shù):理論、算法與實(shí)現(xiàn)