- 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.
推薦閱讀
- TCP/IP入門經(jīng)典(第5版)
- Mastering JavaFX 10
- 區(qū)塊鏈輕松上手:原理、源碼、搭建與應用
- Learning Storm
- 互聯(lián)網(wǎng)安全的40個智慧洞見(2016)
- 計算機通信網(wǎng)絡安全
- Intelligent Mobile Projects with TensorFlow
- 物聯(lián)網(wǎng),So Easy!
- 走近奇妙的物聯(lián)網(wǎng)
- 從物聯(lián)到萬聯(lián):Node.js與樹莓派萬維物聯(lián)網(wǎng)構(gòu)建實戰(zhàn)
- 趣話通信:6G的前世、今生和未來
- 網(wǎng)絡空間作戰(zhàn):機理與籌劃
- Next.js Quick Start Guide
- Advanced Node.js Development
- 區(qū)塊鏈與物聯(lián)網(wǎng):構(gòu)建智慧社會和數(shù)字化世界