regrest
v4.0.1
适用于浏览器和 Node.js 的基于 Micro Promise 的 HTTP 客户端
从浏览器生成 XMLHttpRequest
从 node.js 发出 http 请求
支持 Promise API
内置 TypeScript 支持
| 最新✔ | 最新✔ | 最新✔ | 最新✔ | 最新✔ | 11✔ |
如果您打算支持 Internet Explorer,请确保有一个添加全局Promise对象的 Poly-fill
使用 npm:
$ npm 安装regrest
使用cdn:
<script src="https://cdn.jsdelivr.net/npm/regrest/lib/index.umd.min.js"></script>
Regrest 被设计为最简单的 http 调用方式
执行GET请求
// 使用 NodeJS 或 CommonJS module 导入 const regrest = require("regrest").default;// 或使用 ES6 moduleimport regrest from "regrest";// 使用 Promiseregrest
.get("/人/熊/猪")
// 打印原始响应字符串
.then((响应) => console.log(响应.text))
// 如果发生则打印任何错误
.catch((error) => console.log(`*** Error: ${error}`));// 或者使用新的 async/await 关键字const getGood = async () => {
try {// 将响应存储在变量中 const response = wait regrest.get("/foo/bar.json");// 打印出解析后的responseconsole.log(response.json);
} catch (error) {// 如果发生则打印任何错误console.log(`*** Error: ${error}`);
}};getGood();// 或者使用回调// 我们在这里不这样做执行POST请求
遗憾
.post("/comment", JSON.stringify({ name: "Foo", comment: "Bar" }))
.then((response) => console.log(response.status, response.statusText))
.catch((错误) => console.log(错误));// 默认选项用 *const options = { 标记
method: "GET", // *GET、POST、PUT、DELETE 等
网址:“https://some-domain.com/api/”,
headers: { "Content-Type": "application/json; charset=utf-8" }, // *{}
参数:{UID:9873},
数据: JSON.stringify(data), // *null
最大重定向数: 10, // *5
withCredentials: true, // *false, true};{
// 包含响应的状态代码,例如 404 表示未找到资源,200 表示成功
状态:200,
// 与状态属性相关的消息,例如状态 200 为 OK
状态文本:“确定”,
// 服务器响应的标头
标头:{},
// 响应内容为字符串
文本: ””,
// 响应内容为 JSON
json:{},
// 响应内容在浏览器上为 Blob,在 Node js 上为 Buffer
arrayBuffer:Blob || 的实例缓冲区的实例,
// 以 Blob 形式响应内容
blob:Blob 的实例};regrest.get("/McNullington").catch((错误) => {
if (error.response) {/** * 已发出请求,但服务器响应 * 状态代码超出 2XX 范围 * `error.response` 是响应对象的实例 */console.log(error.response. status);console.log(error.response.statusText);console.log(error.response.headers);// ...
} else if (error.request) {/** * 发出了请求,但没有收到响应 * `error.request` 在浏览器上是 XMLHttpRequest 的实例,在 Node js 上是 * http.ClientRequest 的实例 */console .log(错误.请求);
} else {// 发生了其他事情console.log(error.message);
}});