- Node简介
- 第一个node程序
- module(模块系统)
- npm包管理器
- 模块系统优先级
- 认识http内置模块
- url内置模块
- path内置模块
- fs内置模块
- http模块服务端进阶
- http报文浅析
- url模块进阶
- path模块进阶
- querystring模块进阶
- 了解Buffer和Stream
- os模块
- Buffer模块
- Stream模块
- http模块客户端
- Cookie浅析
http.request(options[, callback])
options
protocol
string 使用的协议。默认为http:
。host
string 请求发送至的服务器的域名或 IP 地址。默认为localhost
。hostname
stringhost
的别名。为了支持url.parse()
,hostname
优先于host
。family
number 当解析host
和hostname
时使用的 IP 地址族。 有效值是4
或6
。当未指定时,则同时使用 IP v4 和 v6。port
number 远程服务器的端口。默认为80
。method
string 指定 HTTP 请求方法的字符串。默认为'GET'
。path
string 请求的路径。默认为'/'
。 应包括查询字符串(如有的话)。如'/index.html?page=12'
。 当请求的路径中包含非法字符时,会抛出异常。 目前只有空字符会被拒绝,但未来可能会变化。headers
Object 包含请求头的对象。timeout
number: 指定 socket 超时的毫秒数。 它设置了 socket 等待连接的超时时间。
callback
Function- 返回: 客户端实例
Node.js 为每台服务器维护多个连接来进行 HTTP 请求。 该函数允许显式地发出请求。
options
可以是一个对象、或字符串、或 URL
对象。 如果 options
是一个字符串,它会被自动使用 url.parse()
解析。 如果它是一个 URL
对象, 它会被默认转换成一个 options
对象。
可选的 callback
参数会作为单次监听器被添加到 'response'
事件。
http.request()
返回一个 http.ClientRequest
类的实例。 ClientRequest
实例是一个可写流。
例子:
const postData = querystring.stringify({
'msg' : 'Hello World!'
});
const options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = http.request(options, (res) => {
console.log(`状态码: ${res.statusCode}`);
console.log(`响应头: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`响应主体: ${chunk}`);
});
res.on('end', () => {
console.log('响应中已无数据。');
});
});
req.on('error', (e) => {
console.error(`请求遇到问题: ${e.message}`);
});
// 写入数据到请求主体
req.write(postData);
req.end();
注意,在例子中调用了 req.end()
。 使用 http.request()
必须总是调用 req.end()
来表明请求的结束,即使没有数据被写入请求主体。