Node.js从无到有-No.8(get/request)

1、get/request

1、http.get()和http.request()方法从后台发起一个http的请求,从而获取远程的资源,http.request()方法返回的是http.ClientRequest的实例,ClinetRequest实例是一个可写流,如果需要POST上传一个文件,那么写入到ClinetRequest对象中去。

2、在官方中我们的request方法是这样描述的:(我直接将文档内容拷贝来)

http.request(options[, callback])#

查看英文版参与翻译

  • options <Object> | <string> | <URL>
    • protocol <string> 使用的协议。默认为 http:
    • host <string> 请求发送至的服务器的域名或 IP 地址。默认为 localhost
    • hostname <string> host 的别名。为了支持 url.parse()hostname 优先于 host
    • family <number> 当解析 host 和 hostname 时使用的 IP 地址族。 有效值是 4 或 6。当未指定时,则同时使用 IP v4 和 v6。
    • port <number> 远程服务器的端口。默认为 80
    • localAddress <string> 为网络连接绑定的本地接口。
    • socketPath <string> Unix 域 Socket(使用 host:port 或 socketPath)。
    • method <string> 指定 HTTP 请求方法的字符串。默认为 'GET'
    • path <string> 请求的路径。默认为 '/'。 应包括查询字符串(如有的话)。如 '/index.html?page=12'。 当请求的路径中包含非法字符时,会抛出异常。 目前只有空字符会被拒绝,但未来可能会变化。
    • headers <Object> 包含请求头的对象。
    • auth <string> 基本身份验证,如 'user:password' 用来计算 Authorization 请求头。
    • agent <http.Agent> | <boolean> 控制 Agent 的行为。 可能的值有:
      • undefined (默认): 对该主机和端口使用 http.globalAgent
      • Agent 对象:显式地使用传入的 Agent
      • false: 创建一个新的使用默认值的 Agent
    • createConnection <Function> 当不使用 agent 选项时,为请求创建一个 socket 或流。 这可以用于避免仅仅创建一个自定义的 Agent 类来覆盖默认的 createConnection 函数。详见 agent.createConnection()。 Any Duplex stream is a valid return value.
    • timeout <number>: 指定 socket 超时的毫秒数。 它设置了 socket 等待连接的超时时间。
  • callback <Function>
  • 返回: <http.ClientRequest>

Node.js 为每台服务器维护多个连接来进行 HTTP 请求。 该函数允许显式地发出请求。

options 可以是一个对象、或字符串、或 URL 对象。 如果 options 是一个字符串,它会被自动使用 url.parse() 解析。 如果它是一个 URL 对象, 它会被默认转换成一个 options 对象。

可选的 callback 参数会作为单次监听器被添加到 'response' 事件。

http.request() 返回一个 http.ClientRequest 类的实例。 ClientRequest 实例是一个可写流。 如果需要通过 POST 请求上传一个文件,则写入到 ClientRequest 对象。

3、我们在用的时候也不是每个都会用到,很多参数都是默认的,我们现在用代码代码实践一下

var http=require('http')
var querystring=require('querystring')

var postData=querystring.stringify({
    'content':'期待下次课程',
    'cid':458
})

var options={
    hostname:'www.imooc.com',
    port:80,
    path:'/course/docoment',
    method:'POST',
    headers:{
        //这里有很多键值对
    }
}

var req=http.request(options,function(res){
    console.log('Status:'+res.statusCode)
    console.log('headers:'+JSON.stringify(res.headers))
    res.on('data',function(chunk){
        console.log(Buffer.isBuffer(chunk))
        console.log(typeof chunk)
    })

    res.on('end',function(){
        console.log('评论完毕')
    })
})


req.on('error',function(e){
    console.log('Error:'+e.message)
})

req.write(postData)
req.end()

4、至于http.get()方法我们也是将官方文档直接搞上来

http.get(options[, callback])#

查看英文版参与翻译

因为大多数请求都是 GET 请求且不带请求主体,所以 Node.js 提供了该便捷方法。 该方法与 http.request() 唯一的区别是它设置请求方法为 GET 且自动调用 req.end()。 注意,回调函数务必消耗掉响应数据,原因详见 http.ClientRequest 章节。

callback 被调用时只传入一个参数,该参数是 http.IncomingMessage 的一个实例。

一个获取 JSON 的例子:

http.get('http://nodejs.org/dist/index.json', (res) => {
  const { statusCode } = res;
  const contentType = res.headers['content-type'];

  let error;
  if (statusCode !== 200) {
    error = new Error('请求失败。\n' +
                      `状态码: ${statusCode}`);
  } else if (!/^application\/json/.test(contentType)) {
    error = new Error('无效的 content-type.\n' +
                      `期望 application/json 但获取的是 ${contentType}`);
  }
  if (error) {
    console.error(error.message);
    // 消耗响应数据以释放内存
    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(`错误: ${e.message}`);
});


猜你喜欢

转载自blog.csdn.net/weixin_37968345/article/details/80780859