Nuxt API Party
Nuxt 模組,提供與多個 API 端點的無縫整合。它為配置的每個 API 端點生成型別安全的可組合項,提供類似於 Nuxt 的 useFetch
和 $fetch
的熟悉開發體驗,同時透過伺服器代理保持 API 憑證安全並消除 CORS 問題。
功能
- 🪅 為每個 API 端點自動生成可組合項
- 🔒 使用 Nuxt 代理路由保護 API 憑證
- 🌐 無 CORS 問題
- 🍱 類似於
useFetch
和$fetch
的熟悉開發體驗 - 🧇 連線所有 API
- 🦾 透過 OpenAPI 規範 完全型別化的 API 客戶端
- 🗃 智慧快取和水合
設定
!提示📖 閱讀文件
npx nuxt module add api-party
基本用法
!提示📖 閱讀文件
將 Nuxt API Party 新增到您的 Nuxt 配置中,並透過為 apiParty
模組選項設定具有以下屬性的端點物件來準備您的第一個 API 連線
// `nuxt.config.ts`
export default defineNuxtConfig({
modules: ['nuxt-api-party'],
apiParty: {
endpoints: {
jsonPlaceholder: {
url: process.env.JSON_PLACEHOLDER_API_BASE_URL!,
// Global headers sent with each request
headers: {
Authorization: `Bearer ${process.env.JSON_PLACEHOLDER_API_TOKEN}`
}
}
}
}
})
如果您將 API 命名為 jsonPlaceholder
,則生成的組合式函式將是
在您的模板或元件中使用這些可組合項
<script setup lang="ts">
const { data, refresh, error, status, clear } = await useJsonPlaceholderData('posts/1')
</script>
<template>
<h1>{{ data?.title }}</h1>
<pre>{{ JSON.stringify(data, undefined, 2) }}</pre>
</template>
!提示 您可以連線任意數量的 API,只需將它們新增到
endpoints
物件中。
💻 開發
- 克隆此倉庫
- 使用
corepack enable
啟用 Corepack - 使用
pnpm install
安裝依賴 - 執行
pnpm run dev:prepare
- 使用
pnpm run dev
啟動開發伺服器
特別感謝
- Dennis Baum 贊助了此包的初始版本。
- Maronbeere 提供的徽標畫素藝術。
許可證
MIT 許可證 © 2022-PRESENT Johann Schopplich
MIT 許可證 © 2025-PRESENT Matthew Messinger