http.get(url[, options][, callback])
曆史
版本 | 變化 |
---|---|
v10.9.0 |
|
v7.5.0 |
|
v0.3.6 | 添加於:v0.3.6 |
參數
url
<string> | <URL>options
<Object> 接受與http.request()
options
,但method
始終設置為GET
。從原型繼承的屬性將被忽略。callback
<Function>- 返回: <http.ClientRequest>
由於大多數請求是沒有正文的 GET 請求,因此 Node.js 提供了這種方便的方法。此方法與
的唯一區別在於它將方法設置為GET 並自動調用http.request()
req.end()
。由於
部分中所述的原因,回調必須注意使用響應數據。http.ClientRequest
callback
使用單個參數調用,該參數是
的實例。http.IncomingMessage
JSON 獲取示例:
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);
相關用法
- Node.js http.globalAgent用法及代碼示例
- Node.js http.Agent.reuseSocket(socket, request)用法及代碼示例
- Node.js http.ServerResponse.setTimeout()用法及代碼示例
- Node.js http.server.keepAliveTimeout用法及代碼示例
- Node.js http.validateHeaderValue(name, value)用法及代碼示例
- Node.js http.ClientRequest.maxHeadersCount用法及代碼示例
- Node.js http.IncomingMessage.httpVersion用法及代碼示例
- Node.js http.IncomingMessage.method用法及代碼示例
- Node.js http.IncomingMessage.aborted用法及代碼示例
- Node.js http.OutgoingMessage.removeHeader(name)用法及代碼示例
- Node.js http.IncomingMessage.complete用法及代碼示例
- Node.js http.validateHeaderName()用法及代碼示例
- Node.js http.IncomingMessage.rawTrailers用法及代碼示例
- Node.js http.OutgoingMessage.hasHeader(name)用法及代碼示例
- Node.js http.IncomingMessage.statusMessage用法及代碼示例
- Node.js http.ServerResponse.socket用法及代碼示例
- Node.js http.ServerResponse.statusCode用法及代碼示例
- Node.js http.ClientRequest.setHeader()用法及代碼示例
- Node.js http.ClientRequest.socket用法及代碼示例
- Node.js http.server.close()用法及代碼示例
- Node.js http.IncomingMessage.rawHeaders用法及代碼示例
- Node.js http.ClientRequest.method用法及代碼示例
- Node.js http.ServerResponse.getHeader()用法及代碼示例
- Node.js http.server.headersTimeout用法及代碼示例
- Node.js http.ClientRequest.reusedSocket用法及代碼示例
注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 http.get(url[, options][, callback])。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。