send an http request

usage

curl

  1. # http client
  2. const url = "https://api.wrdan.com/ip";
  3. const options = {
  4. method: 'GET',
  5. data: {
  6. url: 'https://www.baidu.com',
  7. },
  8. dataType: 'json',
  9. timeout: 15000,
  10. };
  11. const result = await this.app.curl(url, options);

options

method: String

set the request method. The default value is GET. Supports all HTTP methods, such as GET, POST, PUT, DELETE, and PATCH.

data: Object

the request data to be sent, according method automatically select the correct data processing method.

  1. GET,HEAD: use querystring.stringify(data) to process and splice it to the query parameter of the url.
  2. POST,PUT, and DELETE: further judgment is required based on contentType.
    1. contentType = json: it is processed by JSON.stringify(data) and set to body.
    2. others: use querystring.stringify(data) to process and set it to body.
  1. // GET + data
  2. ctx.curl(url, {
  3. data: { foo: 'bar' },
  4. });
  5. // POST + data
  6. ctx.curl(url, {
  7. method: 'POST',
  8. data: { foo: 'bar' },
  9. });
  10. // POST + JSON + data
  11. ctx.curl(url, {
  12. method: 'POST',
  13. contentType: 'json',
  14. data: { foo: 'bar' },
  15. });

content: String|Buffer

the body of the request. If this parameter is set, it will be ignored. Data parameter.

  1. app.curl(url, {
  2. method: 'POST',
  3. // 直接发送原始 xml 数据,不需要 HttpClient 做特殊处理
  4. content: '<xml><hello>world</hello></xml>',
  5. headers: {
  6. 'content-type': 'text/html',
  7. },
  8. });

files: Mixed

file upload. Supported format: String | ReadStream | Buffer | Array | Object.

  1. app.curl(url, {
  2. method: 'POST',
  3. files: '/path/to/read',
  4. data: {
  5. foo: 'other fields',
  6. },
  7. });

Upload multiple files:

  1. app.curl(url, {
  2. method: 'POST',
  3. files: {
  4. file1: '/path/to/read',
  5. file2: fs.createReadStream(__filename),
  6. file3: Buffer.from('mock file content'),
  7. },
  8. data: {
  9. foo: 'other fields',
  10. },
  11. });

stream: ReadStream

set the readable data stream of the request body. The default value is null . Once this parameter is set, the HttpClient is ignored. Data and content .

  1. ctx.curl(url, {
  2. method: 'POST',
  3. stream: fs.createReadStream('/path/to/read'),
  4. });

writeStream: WriteStream

set the writable data stream that accepts response data. The default value is null . Once this parameter is set, the return value result.data will be set null because all data has been written writeStream yes.

  1. ctx.curl(url, {
  2. writeStream: fs.createWriteStream('/path/to/store'),
  3. });

consumeWriteStream: Boolean

wait writeStream the response is received only after it is completely written. The default value is true . This parameter does not recommend modifying the default value unless we clearly know that its side effects are acceptable writeStream the data is incomplete.

method: String

Set the request method. The default value is GET . Supported GET, POST, PUT, DELETE, PATCH

contentType: String

set the request data format. The default value is undefined , the HttpClient is automatically based on data and content parameters are automatically set. Data when it is an object, the default setting is form . Supported JSON the format.
Send in JSON format data :

  1. ctx.curl(url, {
  2. method: 'POST',
  3. data: {
  4. foo: 'bar',
  5. now: Date.now(),
  6. },
  7. contentType: 'json',
  8. });

dataType: String

set the response data format. By default, the original buffer data is directly returned without processing the response data. Supported text and JSON two formats.
Note: set JSON if the response data fails to be parsed JSONResponseFormatError an error occurred.

  1. const jsonResult = await ctx.curl(url, {
  2. dataType: 'json',
  3. });
  4. console.log(jsonResult.data);
  5. const htmlResult = await ctx.curl(url, {
  6. dataType: 'text',
  7. });
  8. console.log(htmlResult.data);

fixJSONCtlChars: Boolean

specifies whether to automatically filter special control characters (U +0000 ~ U + 001F) in response data. The default value is false . Usually, JSON data returned by some CGI systems contains these special control characters, which can be automatically filtered out.。

  1. ctx.curl(url, {
  2. fixJSONCtlChars: true,
  3. dataType: 'json',
  4. });

headers: Object

ustom request headers.

  1. ctx.curl(url, {
  2. headers: {
  3. 'x-foo': 'bar',
  4. },
  5. });

timeout: Number|Array

the request timeout period. Default value: [5000, 5000] , that is, the connection creation timeout is 5 seconds, and the response timeout is 5 seconds.

  1. ctx.curl(url, {
  2. // 创建连接超时 3 秒,接收响应超时 3 秒
  3. timeout: 3000,
  4. });
  5. ctx.curl(url, {
  6. // 创建连接超时 1 秒,接收响应超时 30 秒,用于响应比较大的场景
  7. timeout: [1000, 30000],
  8. });

agent: HttpAgent

this parameter is allowed to overwrite the default HttpAgent. If you do not want to enable KeepAlive, you can set this parameter false .

  1. ctx.curl(url, {
  2. agent: false,
  3. });

httpsAgent: HttpsAgent

this parameter is allowed to overwrite the default HttpsAgent. If you do not want to enable KeepAlive, you can set this parameter false .

  1. ctx.curl(url, {
  2. httpsAgent: false,
  3. });

auth: String

simple logon authorization (Basic Authentication) parameter, the login information will be in plaintext Authorization request the hair to be sent out.

  1. ctx.curl(url, {
  2. // 参数必须按照 `user:password` 格式设置
  3. auth: 'foo:bar',
  4. });

gzip: Boolean

indicates whether gzip response format is supported. Default value: false . After gzip is enabled, the HttpClient is automatically set. Accept-Encoding: gzip the request header is automatically decompressed. Content-Encoding: gzip the response header data.

  1. ctx.curl(url, {
  2. gzip: true,
  3. });

timing: Boolean

whether to enable time measurement for each phase of the request. The default value is false . After timing is enabled, you can result.res.timing get the time measurements (in milliseconds) of each stage of the HTTP request. Through these measurements, we can easily locate the stage in which the slowest environment of the request occurs, and the effect is as Chrome network timing.

Analysis of measured values in each stage of timing:

  • queuing:allocate socket time
  • dnslookup:DNS query time
  • connected:socket three-way handshake connection time
  • requestSent:the time consumed when the request data is completely sent.
  • waiting:The time taken to receive the first byte of response data.
  • contentDownload:It takes time to receive all response data.
    1. const result = await ctx.curl(url, {
    2. timing: true,
    3. });
    4. console.log(result.res.timing);
    5. // {
    6. // "queuing":29,
    7. // "dnslookup":37,
    8. // "connected":370,
    9. // "requestSent":1001,
    10. // "waiting":1833,
    11. // "contentDownload":3416
    12. // }