# @coolaj86/urequest 中文文档

规范地址：https://npmcn.com/package/%40coolaj86/urequest/

版本：1\.3\.7
npm 元数据更新时间：2022-04-05T01:15:50.725Z
中文译文更新时间：2026-11-10T17:56:45.754Z
软件包许可：\(MIT OR Apache-2\.0\)

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40coolaj86/urequest
原文对照：https://npmcn.com/package/%40coolaj86/urequest/?lang=original
源码仓库：https://git.ppl.family/ppl/urequest.js

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：29.3 kB，4 个文件
- 模块格式：CommonJS
- TypeScript 类型：未声明
- 运行依赖：0 个
- 首次发布：2018-06-19T02:01:16.701Z
- 最新版本发布：2019-02-26T08:30:17.033Z
- 近 30 天下载量：198931（2026-10-11 至 2026-11-09，npm 官方下载统计）
- 已发布版本数：18（近 12 个月 0 个）

## 中文简介

用于请求的轻量级空降

## 安装

```sh
npm install @coolaj86/urequest
```

也可以使用：`pnpm add @coolaj86/urequest`、`yarn add @coolaj86/urequest`、`bun add @coolaj86/urequest`

## README

# μ 请求 - 最小化的 HTTP 客户端

用于请求的轻量级替代品(和即时替代).

从零开始写.

## 超简单的使用

μ 请求被设计为用于请求的即时替代. 它支持HTTPS并默认跟随重定向.

```bash
npm install --save @coolaj86/urequest
```

```js
var request = require('@coolaj86/urequest');
request('http://www.google.com', function (error, response, body) {
  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});
```

## 目录

-   [表单](https://npmcn.com/package/%40coolaj86/urequest/#readme-forms)
-   [HTTP 认证](https://npmcn.com/package/%40coolaj86/urequest/#readme-http-authentication)
-   [自定义 HTTP 页眉](https://npmcn.com/package/%40coolaj86/urequest/#readme-custom-http-headers)
-   [Unix 域袜](https://npmcn.com/package/%40coolaj86/urequest/#readme-unix-domain-sockets)
-   [**所有可用的选项**](https://npmcn.com/package/%40coolaj86/urequest/#readme-requestoptions-callback)

## 表单

`urequest` 支持 `application/x-www-form-urlencoded` 财务报告和审定财务报表 `multipart/form-data` 窗体上传.

#### 应用程序/x-www-form-urlencoded(URL-Encoded表格)

URL编码格式简单.

```js
request.post('http://service.com/upload', {form:{key:'value'}})
// or
request.post({url:'http://service.com/upload', form: {key:'value'}}, function(err,httpResponse,body){ /* ... */ })
```

#### 多段/窗体数据(多段窗体上传)

对于 `multipart/form-data` 我们使用 [窗体数据](https://github.com/form-data/form-data) 库 [@ felixge (英语)](https://github.com/felixge)。在大多数情况下,您可以通过 `formData` 选项.

用于 `form-data`,必须分别安装:

```bash
npm install --save form-data@2
```

```js
var formData = {
  // Pass a simple key-value pair
  my_field: 'my_value',
  // Pass data via Buffers
  my_buffer: Buffer.from([1, 2, 3]),
  // Pass data via Streams
  my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
  // Pass multiple values /w an Array
  attachments: [
    fs.createReadStream(__dirname + '/attachment1.jpg'),
    fs.createReadStream(__dirname + '/attachment2.jpg')
  ],
  // Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS}
  // Use case: for some types of streams, you'll need to provide "file"-related information manually.
  // See the `form-data` README for more information about options: https://github.com/form-data/form-data
  custom_file: {
    value:  fs.createReadStream('/dev/urandom'),
    options: {
      filename: 'topsecret.jpg',
      contentType: 'image/jpeg'
    }
  }
};
request.post({url:'http://service.com/upload', formData: formData}, function optionalCallback(err, httpResponse, body) {
  if (err) {
    return console.error('upload failed:', err);
  }
  console.log('Upload successful!  Server responded with:', body);
});
```

见 [窗体数据 REDME](https://github.com/form-data/form-data) 以获取更多信息和实例.

* * *

## HTTP 认证

```js
request.get('http://some.server.com/', {
  'auth': {
    'user': 'username',
    'pass': 'password',
    'sendImmediately': false
  }
});
// or
request.get('http://some.server.com/', {
  'auth': {
    'bearer': 'bearerToken'
  }
});
```

如果通过作为一个选择, `auth` 应为含有下列值的散列:

-   `user` || `username`
-   `pass` || `password`
-   `bearer` (可选)

注意您也可以使用 URL 本身指定基本认证, 如 详细内容见 [RFC 1738 (英语)](http://www.ietf.org/rfc/rfc1738.txt)只要通过 `user:password` 位于主机前 `@` 符号 :

```js
var username = 'username',
    password = 'password',
    url = 'http://' + username + ':' + password + '@some.server.com';

request({url: url}, function (error, response, body) {
   // Do more stuff with 'body' here
});
```

熊儿认证得到支持,并在 `bearer` 值为 可用。 数值可以是a `String` 或一个 `Function` 返回一个 `String`。如果 与 `defaults` 允许单个函数提供 在发送请求时的最后一个已知的符号,或者在苍蝇上计算一个.

[返回顶端](https://npmcn.com/package/%40coolaj86/urequest/#readme-table-of-contents)

* * *

## 自定义 HTTP 页眉

HTTP 密码 信头,例如 `User-Agent`,可以在 `options` 对象. 在下面的例子中,我们叫github API来找出数字 请求寄存器的恒星和分叉。 这需要 自定义 `User-Agent` 标题和https.

```js
var request = require('request');

var options = {
  url: 'https://api.github.com/repos/request/request',
  headers: {
    'User-Agent': 'request'
  }
};

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    var info = JSON.parse(body);
    console.log(info.stargazers_count + " Stars");
    console.log(info.forks_count + " Forks");
  }
}

request(options, callback);
```

[返回顶端](https://npmcn.com/package/%40coolaj86/urequest/#readme-table-of-contents)

* * *

## UNIX 域袜

`urequest` 支持向 [UNIX 域袜](https://en.wikipedia.org/wiki/Unix_domain_socket)。要制作一个,请使用下列 URL 方案:

```js
/* Pattern */ 'http://unix:SOCKET:PATH'
/* Example */ request.get('http://unix:/absolute/path/to/unix.socket:/request/path')
```

说明: `SOCKET` 路径被假定为绝对到主机文件系统的根.

[返回顶端](https://npmcn.com/package/%40coolaj86/urequest/#readme-table-of-contents)

* * *

## 请求( 选项, 回调)

第一个论点可以是: `url` 或一个 `options` 对象。 唯一需要的选择是 `uri`;所有其他都是可选的.

-   `uri` || `url` - 完全合格的uri或解析的url对象 `url.parse()`
-   `method` - http方法( 默认 ): `"GET"`(中文(简体) )
-   `headers` - http页眉(默认: `{}`(中文(简体) )

* * *

-   `body` - PATCH、POST和PUT请求的实体机构。 一定是个 `Buffer`, (中文(简体) ), `String` 或者说 `ReadStream`如果 `json` 实值 `true`,则 `body` 必须是 JSON 的可串行对象.
-   `json` - 套装 `body` 价值和增加值 `Content-type: application/json` 头曰. 此外,将反应机构描述为JSON.

* * *

-   `followRedirect` - 跟踪 HTTP 3xx 回复以重定向(默认 : `true`) (中文(简体) ). 此属性也可以作为函数执行 `response` 对象作为单一参数并应当返回 `true` 如果重定向应当继续,或 `false` 否则.
-   `followAllRedirects` - 跟踪非 GET HTTP 3xx 响应作为方向调整(默认: `false`(中文(简体) )
-   `followOriginalHttpMethod` - 默认我们改用HTTP方法 您可以让此属性重定向到 HTTP 原始方法( 默认 ): `false`(中文(简体) )
-   `maxRedirects` - 要遵循的最大方向数( 默认值 : `10`(中文(简体) )
-   `removeRefererHeader` - 当重定向发生时( 默认 : `false`) (中文(简体) ). **说明:** 如果为真,则在重定向链中保留初始请求中设置的参考页眉.

* * *

-   `encoding` - 编码用于 `setEncoding` 反应数据。 若为 `null`,则 `body` 返回为 `Buffer`。其他任何东西 **(包括 `undefined`(中文(简体) )** 将会通过作为 [编码](http://nodejs.org/api/buffer.html#buffer_buffer) 参数改为 `toString()` (意思是这是有效的) `utf8` (默认情况下)**说明:** 如果您需要二进制数据, 请设定 `encoding: null`. ) (中文(简体) )

* * *

## 方便方法

不同的HTTP方法OD和一些其他的便利也有简写方法.

### 请求. 默认(选项)

这种方法 **返回折叠器** 围绕默认的正常请求 API 无论你给它什么选择.

**说明:** `request.defaults()` **没有** 修改全局请求 API; 相反,它 **返回折叠器** 用于默认设置.

**说明:** 你可以打电话 `.defaults()` 在从 `request.defaults` 以添加/覆盖先前默认的默认值.

例如:

```js
//requests using baseRequest() will set the 'x-token' header
var baseRequest = request.defaults({
  headers: {'x-token': 'my-token'}
})

//requests using specialRequest() will include the 'x-token' header set in
//baseRequest and will also include the 'special' header
var specialRequest = baseRequest.defaults({
  headers: {special: 'special value'}
})
```

### 请求. METHOD( )

这些 HTTP 方法的便利功能就像 `request()` 但已经为您设定了默认方法 :

-   _请求.get ()_默认为 `method: "GET"`。 。 。 .
-   _页:1_默认为 `method: "POST"`。 。 。 .
-   _请求.put()_默认为 `method: "PUT"`。 。 。 .
-   _请求.patch( )_默认为 `method: "PATCH"`。 。 。 .
-   _request.del()/request.delete() 存档副本_默认为 `method: "DELETE"`。 。 。 .
-   _请求。head( )_默认为 `method: "HEAD"`。 。 。 .
-   _请求. 选项( )_默认为 `method: "OPTIONS"`。 。 。 .

* * *

## 调试

调试操作至少有两种方式 `request`数字 :

1.  启动节点进程像 `NODE_DEBUG=urequest node script.js` (单位:千美元)`lib,request,otherlib` 工作也一样.
    
2.  设定 `require('@coolaj86/urequest').debug = true` 任何时间( 这都一样) 作为一.
    

[返回顶端](https://npmcn.com/package/%40coolaj86/urequest/#readme-table-of-contents)

## 常见问题

### @coolaj86/urequest 是什么？

用于请求的轻量级空降

### 如何安装 @coolaj86/urequest？

在项目目录运行 npm install @coolaj86/urequest，或使用 pnpm add / yarn add / bun add。

### @coolaj86/urequest 支持 TypeScript 吗？

该包的 package\.json 没有声明类型入口。需要类型提示时，可以在 npm 上查找社区维护的 @types/coolaj86\_\_urequest 是否存在。

### @coolaj86/urequest 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @coolaj86/urequest 可以商用吗？

@coolaj86/urequest 使用 \(MIT OR Apache-2\.0\) 许可。可在 MIT、Apache-2\.0 中任选其一遵守。选择 MIT 时，宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @coolaj86/urequest 的下载量有多少？

根据 npm 官方下载统计，@coolaj86/urequest 在 2026/10/11 – 2026/11/09 这 30 天内被下载 198,931 次，日均约 6,631 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @coolaj86/urequest 还在维护吗？

最新版本 1\.3\.7 发布于 2019/02/26（7 年前）；至今共发布 18 个版本，其中过去 12 个月发布了 0 个；首次发布于 2018/06/19。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

