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])。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。