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

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.

主站蜘蛛池模板: 乌兰察布市| 兴城市| 普宁市| 衡南县| 贺兰县| 长乐市| 和林格尔县| 彰化县| 凭祥市| 宜州市| 武陟县| 厦门市| 赤峰市| 宣化县| 白河县| 吉首市| 金华市| 吉木萨尔县| 罗平县| 临高县| 乐安县| 九龙城区| 大连市| 若尔盖县| 富锦市| 商南县| 鄱阳县| 资中县| 屏南县| 娱乐| 竹溪县| 仁怀市| 沧州市| 德惠市| 富顺县| 商南县| 江城| 巫溪县| 德格县| 黄龙县| 乌拉特中旗|