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);
}});