http.get(url[, options][, callback])
url<string> | <URL>options<Object> 接受与http.request()相同的options,默认方法为 GET。callback<Function>- 返回: <http.ClientRequest>
由于大多数请求都是没有请求体的 GET 请求,Node.js 提供了这个便捷方法。该方法与 http.request() 的唯一区别在于,它默认将方法设置为 GET,并自动调用 req.end()。回调函数必须注意处理响应数据,原因见 http.ClientRequest 节。
【Since most requests are GET requests without bodies, Node.js provides this
convenience method. The only difference between this method and
http.request() is that it sets the method to GET by default and calls req.end()
automatically. The callback must take care to consume the response
data for reasons stated in http.ClientRequest section.】
callback 会被调用,并且传入一个参数,该参数是 http.IncomingMessage 的实例。
【The callback is invoked with a single argument that is an instance of
http.IncomingMessage.】
获取 JSON 的示例:
【JSON fetching example:】
http.get('http://localhost:8000/', (res) => {
const { statusCode } = res;
const contentType = res.headers['content-type'];
let error;
// Any 2xx status code signals a successful response but
// here we're only checking for 200.
if (statusCode !== 200) {
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
} else if (!/^application\/json/.test(contentType)) {
error = new Error('Invalid content-type.\n' +
`Expected application/json but received ${contentType}`);
}
if (error) {
console.error(error.message);
// Consume response data to free up memory
res.resume();
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
console.log(parsedData);
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
// Create a local server to receive data from
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});
server.listen(8000);