官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 金川县| 丰城市| 克山县| 金川县| 蒙山县| 济源市| 桑植县| 龙川县| 丹寨县| 县级市| 南阳市| 临泉县| 阳泉市| 栾城县| 黔江区| 崇文区| 綦江县| 福建省| 杭锦后旗| 西宁市| 石首市| 新竹县| 望江县| 黔东| 揭西县| 金堂县| 庄河市| 德保县| 泽库县| 奇台县| 新昌县| 从江县| 阿勒泰市| 沛县| 松滋市| 阳谷县| 夏津县| 卫辉市| 通江县| 西畴县| 滕州市|