Welcome 微信登录

首页 / 脚本样式 / JavaScript / node.js中的http.request方法使用说明

方法说明:
函数的功能室作为客户端向HTTP服务器发起请求。
语法:
复制代码 代码如下:
http.get(options, callback)

由于该方法属于http模块,使用前需要引入http模块(var http= require(“http”) )
接收参数:
option   数组对象,包含以下参数:
    host:                  表示请求网站的域名或IP地址(请求的地址)。 默认为"localhost"。
    hostname:        服务器名称,主机名是首选的值。
    port:                  请求网站的端口,默认为 80。
    localAddress:    建立网络连接的本地
    socketPath:       Unix Domain Socket(Domain套接字路径)
    method:            HTTP请求方法,默认是 ‘GET"。
    path:                  请求的相对于根的路径,默认是"/"。QueryString应该包含在其中。例如:/index.html?page=12
    headers:          请求头对象。
    auth:                Basic认证(基本身份验证),这个值将被计算成请求头中的 Authorization 部分。
    callback : 回调,传递一个参数,为 http.ClientResponse的实例。http.request 返回一个 http.ClientRequest 的实例。
例子:
复制代码 代码如下:
var options = {
hostname: "www.google.com",
port: 80,
path: "/upload",
method: "POST"
};
 
var req = http.request(options, function(res) {
console.log("STATUS: " + res.statusCode);
console.log("HEADERS: " + JSON.stringify(res.headers));
res.setEncoding("utf8");
res.on("data", function (chunk) {
console.log("BODY: " + chunk);
});
});
 
req.on("error", function(e) {
console.log("problem with request: " + e.message);
});
 
// write data to request body
req.write("data ");
req.write("data ");
req.end();