Node.js 基础篇(四):内置对象 http / https(1)

http.createServer

http.createServer([options][, requestListener]) #

  • options <Object>
    • IncomingMessage <http.IncomingMessage> 指定要使用的 IncomingMessage 类。 用于扩展原始的 IncomingMessage默认值: IncomingMessage
    • ServerResponse <http.ServerResponse> 指定要使用的 ServerResponse 类。 用于扩展原始的 ServerResponse默认值: ServerResponse
    • insecureHTTPParser <boolean> 使用不安全的 HTTP 解析器,当为 true 时接受无效的 HTTP 标头。 应避免使用不安全的解析器。 有关详细信息,请参阅 --insecure-http-parser默认值: false
    • maxHeaderSize <number> 可选地覆盖此服务器接收到的请求的 --max-http-header-size 值,即请求头的最大长度(以字节为单位)。 默认值: 16384 (16 KB).
  • requestListener <Function>
  • 返回: <http.Server>

返回 http.Server 的新实例。

requestListener 是自动添加到 'request' 事件的函数。

const http = require('http');

// 创建本地服务器来从其接收数据
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({
    data: 'Hello World!'
  }));
});

server.listen(8080, () => {
  console.log('localhost:8080');
});
const http = require('http');

// 创建本地服务器来从其接收数据
const server = http.createServer();

// 监听请求事件
server.on('request', (request, res) => {
  debugger
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({
    data: 'Hello World!'
  }));
});

server.listen(8080, () => {
  console.log('localhost:8080');
});

http.get

http.get(options[, callback])#

http.get(url[, options][, callback]) #

  • url <string>| <URL>
  • options <Object> 接受与 http.request() 相同的 options,但 method 始终设置为 GET。 从原型继承的属性将被忽略。
  • callback <Function>
  • 返回: <http.ClientRequest>

由于大多数请求是没有正文的 GET 请求,因此 Node.js 提供了这个便捷的方法。 此方法与 http.request() 的唯一区别在于,它将方法设置为 GET 并自动调用 req.end()。 因为 http.ClientRequest 章节所述的原因,回调必须注意消费响应数据。

callback 使用单个参数(http.IncomingMessage 的实例)调用。

获取 JSON 的示例:

const http = require('http')
const https = require('https')

const server = http.createServer((request, response) => {
  response.writeHeader(200, {
    'content-type': 'application/json;charset=utf-8',
    'Access-Control-Allow-Origin': '*'
  })
  let data = ''
  https.get('https://www.xiaomiyoupin.com/mtop/mf/resource/data/list', (res) => {
    res.on('data', (chunk) => {
      data += chunk
    })
    res.on('end', () => {
      response.writeHead(200, {
        'content-type': 'application/json;charset=utf-8'
      })
      response.end(data)
    })
  })
})

server.listen(8080, () => {
  console.log('localhost:8080');
})
const http = require('http');

const postData = JSON.stringify({
  'msg': 'Hello World!'
});

const options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(postData)
  }
};

const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});

req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

// 将数据写入请求正文
req.write(postData);
req.end();

http.request

http.request(options[, callback])#

http.request(url[, options][, callback])#

  • url <string> | <URL>
  • options <Object>
    • agent <http.Agent>|<boolean>控制Agent的行为。 可能的值:
      • undefined(默认): 为此主机和端口使用 http.globalAgent
      • Agent 对象: 显式使用传入的 Agent
      • false: 使用具有默认值的新 Agent
    • auth <string> 基本身份验证,即 'user:password' 计算授权标头。
    • createConnection <Function> 当不使用 agent 选项时,生成用于请求的套接字/流的函数。 这可用于避免创建自定义 Agent 类只是为了覆盖默认的 createConnection 函数。 有关详细信息,请参阅 agent.createConnection()。 任何 Duplex 流都是有效的返回值。
    • defaultPort <number> 协议的默认端口。 默认值: 如果使用 Agent 则为 agent.defaultPort,否则为 undefined
    • family <number> 解析 hosthostname 时要使用的 IP 地址族。 有效值为 46。 当未指定时,则将使用 IP v4 和 v6。
    • headers <Object> 包含请求头的对象。
    • hints <number> 可选的 dns.lookup() 提示
    • host <string> 要向其发出请求的服务器的域名或 IP 地址。 默认值: 'localhost'
    • hostname <string> host 的别名。 为了支持 url.parse(),如果同时指定了 hosthostname,则将使用 hostname
    • insecureHTTPParser <boolean> 使用不安全的 HTTP 解析器,当为 true 时接受无效的 HTTP 标头。 应避免使用不安全的解析器。 有关详细信息,请参阅 --insecure-http-parser默认值: false
    • localAddress <string> 用于绑定网络连接的本地接口。
    • localPort <number> 连接的本地端口。
    • lookup <Function> 自定义查找函数。 默认值: dns.lookup().
    • maxHeaderSize <number> 可选地覆盖从服务器接收到的响应的 --max-http-header-size 值,即响应头的最大长度(以字节为单位)。 默认值: 16384 (16 KB).
    • method <string> 指定 HTTP 请求方法的字符串。 默认值: 'GET'
    • path 请求的路径。 应包括查询字符串(如果有)。 例如 '/index.html?page=12'。 当请求路径包含非法字符时抛出异常。 目前,只有空格被拒绝,但将来可能会改变。 默认值: '/'
    • port <string> 远程服务器的端口。 默认值: 如果有设置则为 defaultPort,否则为 80
    • protocol <number> 要使用的协议。 默认值: 'http:'
    • setHost <boolean>: 指定是否自动添加 Host 标头。 默认为 true
    • socketPath <string> Unix 域套接字(如果指定了 hostport 之一,则不能使用,因为其指定了 TCP 套接字)。
    • timeout <number>: 指定套接字超时的数值(以毫秒为单位)。 这将在连接套接字之前设置超时。
    • signal <AbortSignal>: 可用于中止正在进行的请求的中止信号。
  • callback
  • 返回: <http.ClientRequest>

Node.js 为每个服务器维护多个连接以发出 HTTP 请求。 此函数允许显式地发出请求。

url 可以是字符串或 URL 对象。 如果 url 是字符串,则会自动使用 new URL() 解析。 如果是 URL 对象,则会自动转换为普通的 options 对象。

如果同时指定了 urloptions,则合并对象,options 属性优先。

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

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

const http = require('http');

const postData = JSON.stringify({
  'msg': 'Hello World!'
});

const options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(postData)
  }
};

const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});

req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

// 将数据写入请求正文
req.write(postData);
req.end();

在示例中,调用了 req.end()。 使用 http.request() 必须始终调用 req.end() 来表示请求的结束 - 即使没有数据写入请求正文。

如果在请求期间遇到任何错误(无论是 DNS 解析、TCP 级别错误还是实际的 HTTP 解析错误),都会在返回的请求对象上触发 'error' 事件。 与所有 'error' 事件一样,如果没有注册监听器,则会抛出错误。

有一些特殊的标头需要注意。

  • 发送 ‘Connection: keep-alive’ 将通知 Node.js,服务器的连接应该持续到下一个请求。
  • 发送 ‘Content-Length’ 标头将禁用默认的分块编码。
  • 发送 ‘Expect’ 标头将立即发送请求头。 通常,当发送 ‘Expect: 100-continue’ 时,应该设置超时和 'continue' 事件的监听器。 有关更多信息,请参阅 RFC 2616 第 8.2.3 节。
  • 发送授权标头将覆盖使用 auth 选项来计算基本身份验证。

使用 URL 作为 options 的示例:

const options = new URL('http://abc:xyz@example.com');

const req = http.request(options, (res) => {
  // ...
});

在成功的请求中,将按以下顺序触发以下事件:

  • 'socket'

  • 'response'
    
    • res 对象上的 'data',任意次数(如果响应正文为空,则根本不会触发 'data',例如,在大多数重定向中)
    • res 对象上的 'end'
  • 'close'

在连接错误的情况下,将触发以下事件:

  • 'socket'
  • 'error'
  • 'close'

在收到响应之前过早关闭连接的情况下,将按以下顺序触发以下事件:

  • 'socket'
  • 使用具有消息 'Error: socket hang up' 和代码 'ECONNRESET' 的错误的 'error'
  • 'close'

在收到响应之后过早关闭连接的情况下,将按以下顺序触发以下事件:

  • 'socket'

  • 'response'
    
    • res 对象上的 'data',任意次数
  • (在此处关闭连接)

  • res 对象上的 'aborted'

  • res 对象上的 'error',使用具有消息 'Error: aborted' 和代码 'ECONNRESET' 的错误。

  • 'close'

  • res 对象上的 'close'

如果在分配套接字之前调用 req.destroy(),则将按以下顺序触发以下事件:

  • (在此处调用 req.destroy()
  • 使用具有消息 'Error: socket hang up' 和代码 'ECONNRESET' 的错误的 'error'
  • 'close'

如果在连接成功之前调用 req.destroy(),则将按以下顺序触发以下事件:

  • 'socket'
  • (在此处调用 req.destroy()
  • 使用具有消息 'Error: socket hang up' 和代码 'ECONNRESET' 的错误的 'error'
  • 'close'

如果在收到响应之后调用 req.destroy(),则将按以下顺序触发以下事件:

  • 'socket'

  • 'response'
    
    • res 对象上的 'data',任意次数
  • (在此处调用 req.destroy()

  • res 对象上的 'aborted'

  • res 对象上的 'error',使用具有消息 'Error: aborted' 和代码 'ECONNRESET' 的错误。

  • 'close'

  • res 对象上的 'close'

如果在分配套接字之前调用 req.abort(),则将按以下顺序触发以下事件:

  • (在此处调用 req.abort()
  • 'abort'
  • 'close'

如果在连接成功之前调用 req.abort(),则将按以下顺序触发以下事件:

  • 'socket'
  • (在此处调用 req.abort()
  • 'abort'
  • 使用具有消息 'Error: socket hang up' 和代码 'ECONNRESET' 的错误的 'error'
  • 'close'

如果在收到响应之后调用 req.abort(),则将按以下顺序触发以下事件:

  • 'socket'

  • 'response'
    
    • res 对象上的 'data',任意次数
  • (在此处调用 req.abort()

  • 'abort'

  • res 对象上的 'aborted'

  • res 对象上的 'error',使用具有消息 'Error: aborted' 和代码 'ECONNRESET' 的错误。

  • 'close'

  • res 对象上的 'close'

设置 timeout 选项或使用 setTimeout() 函数将不会中止请求或执行除添加 'timeout' 事件外的任何操作。

传入 AbortSignal 然后在相应的 AbortController 上调用 abort,与在请求本身上调用 .destroy() 的行为相同。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

__畫戟__

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值