### Install Project Dependencies Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/contributing/03-developing-guidelines.md Install all necessary project dependencies using pnpm. ```bash pnpm install ``` -------------------------------- ### Install Uniapp Adapter with npm Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/01-request-adapter/05-uniapp.md Use this command to install the necessary packages via npm. ```bash npm install alova @alova/adapter-uniapp @alova/shared --save ``` -------------------------------- ### Install Uniapp Adapter with yarn Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/01-request-adapter/05-uniapp.md Use this command to install the necessary packages via yarn. ```bash yarn add alova @alova/adapter-uniapp @alova/shared ``` -------------------------------- ### Install npm Package Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/01-request-adapter/03-xhr.md Install the AlovaJS core and the XMLHttpRequest adapter using npm. ```bash npm install alova @alova/adapter-xhr --save ``` -------------------------------- ### Install Uniapp Adapter with pnpm Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/01-request-adapter/05-uniapp.md Use this command to install the necessary packages via pnpm. ```bash pnpm install alova @alova/adapter-uniapp @alova/shared ``` -------------------------------- ### Install Axios Adapter with npm Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/01-request-adapter/04-axios.md Install the Alova core, the Axios adapter, and Axios itself using npm. ```bash npm install alova @alova/adapter-axios axios --save ``` -------------------------------- ### Install Process Shared Adapter Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/02-storage-adapter/01-psc.md Install the alova and @alova/psc packages using npm, yarn, or pnpm. ```bash # npm npm install alova @alova/psc --save # yarn yarn add alova @alova/psc # npm pnpm install alova @alova/psc ``` -------------------------------- ### Install Alova Taro Adapter with npm Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/01-request-adapter/06-taro.md Install the Alova core and the Taro adapter using npm. ```bash npm install alova @alova/adapter-taro --save ``` -------------------------------- ### Install yarn Package Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/01-request-adapter/03-xhr.md Install the AlovaJS core and the XMLHttpRequest adapter using yarn. ```bash yarn add alova @alova/adapter-xhr ``` -------------------------------- ### Install Alova Mock Plugin Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/01-request-adapter/01-alova-mock.md Install the Alova mock plugin using npm, yarn, or pnpm. ```bash npm install alova @alova/mock --save ``` ```bash yarn add alova @alova/mock ``` ```bash pnpm install alova @alova/mock ``` -------------------------------- ### SessionStorage Adapter Example Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/06-advanced/02-custom/02-storage-adapter.md An example of a custom storage adapter that utilizes `sessionStorage` for persistence. It includes methods for setting, getting, removing, and clearing data, with JSON stringification/parsing for structured data. ```javascript const sessionStorageAdapter = { set(key, value) { sessionStorage.setItem(key, JSON.stringify(value)); }, get(key) { const data = sessionStorage.getItem(key); return data ? JSON.parse(data) : data; }, remove(key) { sessionStorage.removeItem(key); }, clear() { sessionStorage.clear(); } }; ``` -------------------------------- ### Install File Storage Adapter Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/02-storage-adapter/02-file.md Install the alova and @alova/storage-file packages using npm, yarn, or pnpm. ```bash # npm npm install alova @alova/storage-file --save # yarn yarn add alova @alova/storage-file # npm pnpm install alova @alova/storage-file ``` -------------------------------- ### Install pnpm Package Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/01-request-adapter/03-xhr.md Install the AlovaJS core and the XMLHttpRequest adapter using pnpm. ```bash pnpm install alova @alova/adapter-xhr ``` -------------------------------- ### Install Axios Adapter with pnpm Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/01-request-adapter/04-axios.md Install the Alova core, the Axios adapter, and Axios itself using pnpm. ```bash pnpm install alova @alova/adapter-axios axios ``` -------------------------------- ### Install Alova Taro Adapter with yarn Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/01-request-adapter/06-taro.md Install the Alova core and the Taro adapter using yarn. ```bash yarn add alova @alova/adapter-taro ``` -------------------------------- ### Install Alova Taro Adapter with pnpm Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/01-request-adapter/06-taro.md Install the Alova core and the Taro adapter using pnpm. ```bash pnpm install alova @alova/adapter-taro ``` -------------------------------- ### Install Redis Storage Adapter Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/02-storage-adapter/03-redis.md Install the necessary packages for the Redis storage adapter using npm, yarn, or pnpm. ```bash # npm npm install alova @alova/storage-redis --save # yarn yarn add alova @alova/storage-redis # npm pnpm install alova @alova/storage-redis ``` -------------------------------- ### Install Axios Adapter with yarn Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/01-request-adapter/04-axios.md Install the Alova core, the Axios adapter, and Axios itself using yarn. ```bash yarn add alova @alova/adapter-axios axios ``` -------------------------------- ### Making a GET Request (React) Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/01-request-adapter/06-taro.md Example of making a GET request using the Alova instance in a React component. Configuration options for Taro.request can be passed. ```jsx const list = () => alovaInst.Get('/list', { // The set parameters will be passed to Taro.request enableHttp2: true }); const App = () => { const { loading, data } = useRequest(list); return ( { loading ? Loading... : null } The requested data is: { JSON.stringify(data) } ) }; ``` -------------------------------- ### XMLHttpRequest HTTP Adapter Example Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/06-advanced/02-custom/01-http-adapter.md This example shows how to create a custom HTTP adapter using XMLHttpRequest. It is intended for demonstration purposes and requires further implementation to be fully functional. Note that 'config' and 'updateDownloadProgress'/'updateUploadProgress' are assumed to be defined elsewhere. ```javascript function XMLHttpRequestAdapter(requestElements, methodInstance) { // Deconstruct the data needed const { url, type, data, headers } = config; // Send request const xhr = new XMLHttpRequest(); xhr.open(type, url); for (const key in headers) { xhr.setRequestHeader(key, headers[key]); } const responsePromise = new Promise((resolve, reject) => { xhr.addEventListener('load', event => { // Process response data resolve(/* ... */); }); xhr.addEventListener('error', event => { // Process request error reject(/* ... */); }); }); xhr.send(JSON.stringify(data)); return { // Asynchronous function that returns response data response: () => responsePromise, // Asynchronous function that returns the response header headers: () => responsePromise.then(() => xhr.getAllResponseHeaders()), abort: () => { xhr.abort(); }, // Download progress information, continuously call updateDownloadProgress internally to update the download progress onDownload: updateDownloadProgress => { xhr.addEventListener('progress', event => { // Data receiving progress updateDownloadProgress(event.total, event.loaded); }); }, // Upload progress information, continuously call updateUploadProgress internally to update the upload progress onUpload: updateUploadProgress => { xhr.upload.onprogress = event => { updateUploadProgress(event.total, event.loaded); }; } }; } ``` -------------------------------- ### Install Alova with pnpm Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/02-getting-started/02-quick-start.md Use pnpm to install Alova, a fast, disk-space-efficient package manager. ```bash pnpm add alova ``` -------------------------------- ### Install Alova with npm Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/02-getting-started/02-quick-start.md Use npm to install the Alova library. This is the most common way to add Alova to your project. ```bash npm install alova --save ``` -------------------------------- ### Install Alova and Vue Options Package Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/03-framework/07-vue-options.md Install the core Alova library along with the Vue Options integration package using npm, yarn, or pnpm. ```bash npm install alova @alova/vue-options --save ``` ```bash yarn add alova @alova/vue-options ``` ```bash pnpm install alova @alova/vue-options ``` -------------------------------- ### Create GET Request Method Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/api/01-alova.md Use `alovaInstance.Request` to create a GET request method. This is a general way to define requests, and specific methods like `Get` offer more direct syntax. ```typescript const getUsers = alovaInstance.Request({ url: '/users', method: 'GET', params: { id: 1 } // ... }); ``` -------------------------------- ### Install Alova and Axios Adapter Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/07-project/02-migration/02-from-axios.md Install the necessary packages for Alova and its Axios adapter using npm, yarn, or pnpm. ```bash # npm npm install alova @alova/adapter-axios # yarn yarn add alova @alova/adapter-axios # pnpm pnpm install alova @alova/adapter-axios ``` -------------------------------- ### Multi-Module Type Replacement Configuration Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/04-devtool-plugins/06-import-type.md Example demonstrating how to configure type replacements for multiple modules simultaneously using the importType plugin. ```javascript // Configure type replacements for multiple modules simultaneously importType({ bar: ['Apis', 'Foo'], '@types/bar': ['Bar'], 'vue|type': ['Vue'] }); ``` -------------------------------- ### Install Alova with bun Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/02-getting-started/02-quick-start.md Use bun, a fast JavaScript runtime, to add Alova to your project. ```bash bun add alova ``` -------------------------------- ### Initialize Alova Instance for Server Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/02-getting-started/03-basic/08-server.md Initialize an Alova instance for server-side environments using the fetch adapter. This setup is suitable for Node.js, Deno, and Bun. ```javascript import { createAlova } from 'alova'; import adapterFetch from 'alova/fetch'; const alovaInstance = createAlova({ requestAdapter: adapterFetch() }); alovaInstance.Get(...); alovaInstance.Post(...); ``` -------------------------------- ### Initialize Changeset Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/contributing/03-developing-guidelines.md Start the changeset process to declare changes for packages, which helps in versioning and changelog generation. ```bash pnpm run changeset ``` -------------------------------- ### Install Alova with yarn Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/02-getting-started/02-quick-start.md Use yarn to add Alova to your project dependencies. ```bash yarn add alova ``` -------------------------------- ### alova.Get() Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/api/01-alova.md Creates a method instance for a GET request. It takes a URL and an optional configuration object. ```APIDOC ## alova.Get() ### Description Creates a method instance for a GET request. ### Method GET ### Endpoint [URL] ### Parameters #### Path Parameters None #### Query Parameters - **params** (object) - Optional - Request parameters. #### Request Body None ### Request Example ```ts const getUsers = alovaInstance.Get('/users', { params: { id: 1 } // ... }); ``` ### Response #### Success Response (200) - **method instance** - Returns a method instance. #### Response Example ```json { "example": "method instance" } ``` ### Configuration Parameters - **headers** (object) - Request header. - **params** (object) - Request parameters. - **name** (string) - Method object name. - **timeout** (number) - Request timeout. - **cacheFor** (cacheForConfig) - Response cache time. - **hitSource** (string) - Hit the source method instance. When the source method instance request succeeds, the cache of the current method instance will be invalidated. - **transform** (function) - Transform response data. - **shareRequest** (boolean) - Request-level shared request switch. - **meta** (any) - Method metadata. ``` -------------------------------- ### Make a GET request with Alova Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/02-getting-started/02-quick-start.md Send a GET request using the Alova instance. The fetch adapter returns a Response instance directly. ```javascript const response = await alovaInstance.Get('https://alovajs.dev/user/profile'); ``` -------------------------------- ### Setup Nuxt Adapter for AlovaJS Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/06-advanced/01-in-depth/09-ssr.md Configure the Nuxt adapter for AlovaJS by importing `createAlova` and `NuxtHook`. Ensure `useNuxtApp` is specified in the `nuxtApp` option. ```javascript import { createAlova } from 'alova'; import NuxtHook from 'alova/nuxt'; export const alovaInstance = createAlova({ // ... statesHook: NuxtHook({ nuxtApp: useNuxtApp // useNuxtApp must be specified }) }); ``` -------------------------------- ### Generate API Information (Single Project) Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/api/07-wormhole.md Generates API information based on the provided configuration object. This example assumes configuration files exist only in the root directory. ```typescript import { readConfig, generate } from '@alova/wormhole'; const config = await readConfig(); const results = await generate(config); ``` -------------------------------- ### Configure Memory and Storage Cache Adapters Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/release-notes-v3.md Demonstrates setting up a two-level cache system using LRUCache for the first level (memory) and a custom asynchronous adapter for the second level (storage, e.g., Redis). ```javascript const { LRUCache } = require('lru-cache'); const { createClient } = require('redis'); const client = createClient(/*...*/); const alovaInst = createAlova({ // ... // l1 is the highest priority cache, that is, the original memory cache l1Cache: new LRUCache(), // l2 is a lower memory cache, that is, the original persistent cache l2Cache: { set: async (key, [data, expireTs]) => { await client.set(key, data, { EX: Number((expireTs - Date.now()) / 1000) }); }, get: async key => client.get(key), remove: async key => client.set(key, '', 0) } }); ``` -------------------------------- ### Making a GET Request (Vue) Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/01-request-adapter/06-taro.md Example of making a GET request using the Alova instance in a Vue component. Configuration options for Taro.request can be passed. ```html ``` -------------------------------- ### Server-Side Rate Limiting with sendCaptcha Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/release-notes-v3.md Example of using server-side hooks like useRateLimit and sendCaptcha for implementing rate limiting, specifically for sending a captcha. This requires 'alova/server' to be installed. ```javascript const { useRateLimit, sendCaptcha } = require('alova/server'); import adapterFetch from 'alova/fetch'; const alova = createAlova({ requestAdapter: adapterFetch() }); const requestCaptcha = mobile => alova.Get('/api/captcha', { params: { mobile } }); try { await sendCaptcha(requestCaptcha, { key: mobile, countdown: 60 }); } catch (error) { throw new Error('Send failed'); } ``` -------------------------------- ### Use Alova for New Requests Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/07-project/02-migration/02-from-axios.md Define and use Alova request methods within your components. This example shows how to create a GET request for user data and use it with `useRequest` hook. ```javascript const getUser = id => alovaInst.Get(`/user/${id}`); // Use in components const { loading, data, error } = useRequest(getUser(userId)); ``` -------------------------------- ### Use Alova via CDN with Vue Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/07-project/03-troubleshooting.md This example demonstrates how to include and use Alova with Vue.js via CDN. Ensure all necessary Alova and Vue scripts are loaded. ```html
Loading...
{{ error.message }}
responseData: {{ data }}
``` -------------------------------- ### Use Alova via CDN with React Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/07-project/03-troubleshooting.md This example shows how to integrate Alova into a React application using CDN links. It includes React, ReactDOM, Babel, and Alova scripts. ```html
``` -------------------------------- ### Manual Request Status Management with Axios Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/about/02-comparison.md When using axios alone, you must manually manage loading, data, and error states. This example shows the typical setup in Vue 3. ```javascript // vue3 example const loading = ref(false); const data = ref({}); const error = ref(null); const request = async () => { try { loading.value = true; data.value = await axios.get('/xxx'); } catch (e) { error.value = e; } loading.value = false; }; mounted(request); ``` -------------------------------- ### Configure Global Response Cache Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/02-getting-started/03-basic/04-alova.md Set global response cache durations for different HTTP methods. Caching is disabled for GET requests and set to 1 hour for POST requests in this example. ```typescript const alovaInstance = createAlova({ // ... cacheFor: { GET: 0, // Close all GET caches POST: 60 * 60 * 1000 // Set all POST caches for 1 hour } }); ``` -------------------------------- ### Install @alova/wormhole Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/api/07-wormhole.md Install the `@alova/wormhole` package as a development dependency using npm, yarn, or pnpm. ```bash # npm npm i @alova/wormhole --save-dev # yarn yarn add @alova/wormhole --dev # pnpm pnpm add @alova/wormhole -D ``` -------------------------------- ### Install @alova/wormhole with pnpm Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/02-getting-started/09-openapi-integration.md Use this command to install the @alova/wormhole package as a development dependency using pnpm. ```bash pnpm add @alova/wormhole -D ``` -------------------------------- ### Install @alova/wormhole with yarn Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/02-getting-started/09-openapi-integration.md Use this command to install the @alova/wormhole package as a development dependency using yarn. ```bash yarn add @alova/wormhole --dev ``` -------------------------------- ### Install @alova/wormhole with npm Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/02-getting-started/09-openapi-integration.md Use this command to install the @alova/wormhole package as a development dependency using npm. ```bash npm install @alova/wormhole --save-dev ``` -------------------------------- ### Run All Unit Tests Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/contributing/03-developing-guidelines.md Execute all unit tests for the project using the command line. ```bash pnpm run test ``` -------------------------------- ### Create Alova instance with Deno Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/02-getting-started/02-quick-start.md Initialize an Alova instance using the fetch adapter within a Deno environment, leveraging npm specifiers for imports. ```javascript import { createAlova } from 'npm:alova'; import adapterFetch from 'npm:alova/fetch'; const alovaInstance = createAlova({ requestAdapter: adapterFetch(), responded: response => response.json() }); ``` -------------------------------- ### Create IndexedDB Instance and Operations Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/07-project/01-best-practice/04-manage-cache-by-indexeddb.md Sets up an IndexedDB database and defines functions to add and retrieve image data. Ensure the database and object store are created correctly. ```javascript const dbVersion = 1; let dbInstance; const request = window.indexedDB.open('MyTestDatabase', dbVersion); request.onupgradeneeded = ({ target }) => { dbInstance = target.result; const imgStore = dbInstance.createObjectStore('images', { autoIncrement: true }); imgStore.createIndex('fileName', 'fileName', { unique: true }); }; request.onerror = () => { throw new Error('Database open fail'); }; request.onsuccess = ({ target }) => { dbInstance = target.result; }; // Add new data to IndexedDB export const addImage2Cache = async (fileName, data) => { const tx = dbInstance.transaction(['images'], 'readwrite'); const request = tx.objectStore('images').add({ fileName, data }); return new Promise((resolve, reject) => { request.onerror = () => { reject('data add fail'); }; request.onsuccess = ({ result }) => { resolve(result); }; }); }; // Get file data according to fileName export const getImageFromCache = async fileName => { const tx = dbInstance.transaction(['images']); const request = tx.objectStore('images').index('fileName').get(fileName); return new Promise((resolve, reject) => { request.onerror = () => { reject('data add fail'); }; request.onsuccess = ({ target }) => { resolve(target.result); }; }); }; ``` -------------------------------- ### Initialize alova.config with alova init command Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/api/07-wormhole.md Use the `alova init` command to generate an `alova.config` configuration file in the current directory. The `--type` parameter allows specifying the configuration file type (e.g., `auto`, `ts`, `commonjs`), defaulting to `auto`. Use `--cwd` to specify the working directory for generation. ```bash alova init [-t, --type ] [-c --cwd ] ``` -------------------------------- ### Create FileStorageAdapter Instance Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/02-storage-adapter/02-file.md Instantiate FileStorageAdapter and configure the storage directory. The directory will be created if it doesn't exist. This adapter can be used with alova's l2Cache. ```javascript const { createAlova } = require('alova'); const FileStorageAdapter = require('@alova/storage-file'); const dir = '~/alova/storage'; const fileAdapter = new FileStorageAdapter({ directory: dir }); const alovaInstance = createAlova({ // ... l2Cache: fileAdapter }); ``` -------------------------------- ### SolidJS: Managing SSE Data and Connection State Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/03-client/01-strategy/14-use-sse.md This SolidJS example demonstrates using the `useSSE` hook to handle Server-Sent Events. It includes state management for connection status and received data, along with UI elements for interaction. ```jsx import { createSignal } from 'solid-js'; const App = () => { const [dataList, setDataList] = createSignal([]); const { data, readyState, close, send } = useSSE(postMethodHandler) .onMessage(({ data }) => { setDataList(prevList => [...prevList, data]); }) .onError(error => { // ... }); return (
{readyState() === 0 ? 'Connecting' : readyState() === 1 ? 'Connected' : 'Disconnected'}
Last received data: {data()}
    {item =>
  • {item}
  • }
); }; ``` -------------------------------- ### Basic useSerialWatcher Usage Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/03-client/01-strategy/12-use-serial-watcher.md Demonstrates the basic setup of useSerialWatcher, passing an array of request handlers and watched states. The `immediate: true` option triggers the requests upon component mount. Use the `send` function to manually trigger requests with arguments. ```javascript import { useSerialWatcher } from 'alova/client'; const { loading, data, error, send, onSuccess, onError, onComplete } = useSerialWatcher( [ (...args) => request1(args), (response1, ...args) => request2(response1, args), (response2, ...args) => request3(response2, args) ], [watchedState1, watchedState2], { immediate: true } ); send(1, 2, 3); ``` -------------------------------- ### Migrate Axios GET Request to Alova Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/07-project/02-migration/02-from-axios.md Replace `axios.get` with `alovaInst.Get` to migrate GET requests. The method signature and options remain similar. ```javascript // Original get request const todoList = id => axios.get('/todo'); // After change const todoList = id => alovaInst.Get('/todo'); ``` -------------------------------- ### Initialize SSE with useSSE Hook Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/03-client/01-strategy/14-use-sse.md Import and use the `useSSE` hook to manage Server-Sent Events. It returns various properties and methods for controlling the connection and handling data. The `postMethodHandler` defines the request to be made. ```javascript import { useSSE } from 'alova/client'; const postMethodHandler = (value: string) => alova.Post('/api/source', null, { headers: { 'Content-Type': 'application/json' }, param: { key: value } }); const { data, eventSource, readyState, onOpen, onMessage, onError, on, send, close } = useSSE(postMethodHandler, { credentials: 'include', initialData: 'initial-data', }); ``` -------------------------------- ### Create Configuration File Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/api/07-wormhole.md Creates a new configuration file for Alova. Use this to initialize project configuration. ```typescript import { createConfig } from '@alova/wormhole'; await createConfig(); ``` -------------------------------- ### Create GET Request Method Instance Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/api/01-alova.md Use `alova.Get()` to create a method instance for a GET request. You can configure request parameters like `params` and `headers`. ```typescript const getUsers = alovaInstance.Get('/users', { params: { id: 1 } // ... }); ``` -------------------------------- ### Configure Memory Cache for GET Request Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/05-cache/01-mode.md Set the cache mode to 'memory' and specify the expiration time in milliseconds for a GET request. Use `Infinity` for no expiration or a non-positive number to disable caching. ```javascript alovaInstance.GET('/todo/list', { // ... // highlight-start cacheFor: { // Set the cache mode to memory mode mode: 'memory', // Unit is milliseconds // When set to `Infinity`, it means that the data will never expire. When set to 0 or a negative number, it means that it will not be cached expire: 60 * 10 * 1000 } // highlight-end }); ``` -------------------------------- ### Listen to Preloading Events Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/03-client/01-strategy/04-use-pagination.md Use `fetching`, `onFetchSuccess`, `onFetchError`, and `onFetchComplete` to monitor and react to preloading status and events. ```javascript const { // Preloading status fetching, // Preloading success event binding function onFetchSuccess, // Preloading error event binding function onFetchError, // Preloading completion event binding function onFetchComplete } = usePagination((page, pageSize) => queryStudents(page, pageSize), { // ... }); ``` -------------------------------- ### useAutoRequest with Configuration Options Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/03-client/01-strategy/07-use-auto-request.md Shows how to configure useAutoRequest with options such as enabling/disabling browser events, setting throttle time, and configuring polling. ```javascript const { loading, data, error, onSuccess, onError, onComplete } = useAutoRequest( () => method(), { /** * Browser display hide trigger * @default true */ enableVisibility: true, /** * Triggered by browser focus * @default true */ enableFocus: true, /** * Triggered by network reconnection * @default true */ enableNetwork: true, /** *Throttling time, only one request will be sent if triggered multiple times within a certain period, unit ms * @default 1000 */ throttle: 1000, /** * The time of polling request, effective when set greater than 0, unit ms * @default 0 */ pollingTime: 2000 //Other parameters are the same as useRequest... } ); ``` -------------------------------- ### Set Different Expiration Times Globally for GET Requests Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/05-cache/01-mode.md Globally configure distinct cache expiration times for GET requests based on method metadata. The `expire` function checks for a `setDiffExpire` flag to apply different durations for L1 and L2 caches, otherwise using a default 5-minute expiration. ```js const alovaInst = createAlova({ // ... cacheFor: { GET: { mode: 'restore', expire: ({ method, mode }) => { if (method.meta.setDiffExpire) { // Set 5 minutes cache in l1 cache and 1 day cache in l2 cache return mode === 'memory' ? 5 * 60 : 24 * 60 * 60; } return 5 * 60; } } } }); ``` -------------------------------- ### createAlova() Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/api/01-alova.md Creates an Alova instance with the specified configuration options. This is the primary way to set up Alova for your application. ```APIDOC ## createAlova() ### Description Creates an Alova instance with the specified configuration options. ### Signature ```ts function createAlova(options?: AlovaOptions): Alova; ``` ### Parameters #### Options - **requestAdapter** (object) - Required - Request adapter configuration. - **id** (string | number) - Optional - Alova instance ID. - **baseURL** (string) - Optional - Base path for requests. - **statesHook** (object) - Optional - State management hook. - **timeout** (number) - Optional - Request timeout in milliseconds. - **cacheFor** (object) - Optional - Local cache configuration. - **l1Cache** (object) - Optional - Level 1 cache adapter. - **l2Cache** (object) - Optional - Level 2 cache adapter. - **beforeRequest** (function) - Optional - Hook executed before a request is sent. - **responded** (object | function) - Optional - Hook executed when a response is received. - **shareRequest** (boolean) - Optional - Enables sharing of identical requests. - **cacheLogger** (boolean | null | function) - Optional - Enables or configures cache logging. - **snapshots** (number) - Optional - Limits the number of snapshots for method matching. ### Return Alova instance. ### Example ```ts import { createAlova } from 'alova'; import VueHook from 'alova/vue'; import adapterFetch from 'alova/fetch'; const alova = createAlova({ baseURL: 'https://example.com', statesHook: VueHook, requestAdapter: adapterFetch(), timeout: 3000 // ... other options }); ``` ``` -------------------------------- ### Deprecated matchSnapshotMethod Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/release-notes-v3.md Use `alova.snapshots.match` in v3.0 to get method instance snapshots by name. ```javascript ### Deprecated `matchSnapshotMethod` In alova@3.0, `alova.snapshots.match` is used to obtain the instance snapshot under the corresponding alova. ```js alova.snapshots.match('method-name'); ``` ``` -------------------------------- ### Basic useSerialRequest Usage Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/03-client/01-strategy/11-use-serial-request.md Demonstrates the basic setup of useSerialRequest with an array of request handlers. The `send` function triggers the serial execution, and arguments are passed through. Set `immediate: false` to prevent automatic execution on mount. ```javascript import { useSerialRequest } from 'alova/client'; const { loading, data, error, send, onSuccess, onError, onComplete } = useSerialRequest( [ (...args) => request1(args), (response1, ...args) => request2(response1, args), (response2, ...args) => request3(response2, args) ], { immediate: false } ); send(1, 2, 3); ``` -------------------------------- ### Create Alova instance with ES Module Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/02-getting-started/02-quick-start.md Initialize an Alova instance using the fetch adapter in an ES Module environment. Configure response handling to parse JSON. ```javascript import { createAlova } from 'alova'; import adapterFetch from 'alova/fetch'; const alovaInstance = createAlova({ requestAdapter: adapterFetch(), responded: response => response.json() }); ``` -------------------------------- ### Reset List Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/03-client/01-strategy/04-use-pagination.md Clears all cached data and reloads the list starting from the first page. ```APIDOC ## reload ### Description Clears all caches and reloads the list from the first page. ### Signature ```typescript declare function reload(): Promise; ``` ### Returns * A promise indicating whether the reset was successful (available from v3.1.0+). ``` -------------------------------- ### Load Todo List with useSQRequest Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/03-client/01-strategy/09-seamless-data-interaction/04-conservative-request.md Loads and displays page data using `useSQRequest` with an initial empty array. ```javascript import { useSQRequest } from 'alova/client'; import { todoList } from './api.js'; const { data, loading, error } = useSQRequest(todoList, { initialData: [] }); ``` -------------------------------- ### SolidJS Search with useWatcher Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/03-client/01-strategy/02-use-watcher.md This SolidJS example illustrates the use of the useWatcher hook for implementing a search feature. It's beneficial for Solid applications that require real-time data updates in response to search queries. ```jsx import { useWatcher, createFetchApi, createService, } from '@alovajs/alova'; import { createSignal } from 'solid-js'; const searchApi = createFetchApi(() => ({ baseURL: 'https://mock.shop.com', })); const searchService = createService(searchApi); function Search() { const [keyword, setKeyword] = createSignal(''); const list = useWatcher( () => keyword(), () => { return searchService.search(keyword()); } ); return (
setKeyword(e.target.value)} /> {list.loading &&
Loading...
} {list.data?.todos.map((todo: any) => (
{todo.title}
))}
); } export default Search; ``` -------------------------------- ### Simplified Request with Await Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/02-getting-started/03-basic/03-method.md A more concise way to send a request and get the response directly using `await`. ```javascript const response = await alovaInstance.Get('/api/user'); ``` -------------------------------- ### Create UniApp Alova Instance Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/01-request-adapter/05-uniapp.md Initialize alova with the UniApp adapter. This provides Request Adapter, Storage Adapter, and VueHook. ```javascript import { createAlova } from 'alova'; import AdapterUniapp from '@alova/adapter-uniapp'; const alovaInst = createAlova({ baseURL: 'https://api.alovajs.org', ...AdapterUniapp() }); ``` -------------------------------- ### Modify Parameter Type Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/04-devtool-plugins/03-payload-modifier.md Example of changing the type of a specific field (`age`) within the `params` scope to `number`. ```javascript // Change the `age` field in `params` to `number` type payloadModifier([ { scope: 'params', match: 'age', handler: () => 'number' } ]); ``` -------------------------------- ### alova.Options() Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/api/01-alova.md Creates a method instance for making OPTIONS requests. It takes a URL and optional configuration. ```APIDOC ## alova.Options() ### Description Create a method instance for OPTIONS request. ### Method OPTIONS ### Endpoint [URL] ### Parameters #### Path Parameters - **url** (string) - Required - request address - **config** (AlovaMethodCreateConfig) - Optional - configuration parameters, parameter type is the same as [alova.Get](#alovaget) ### Return method instance ``` -------------------------------- ### Bind Upload Progress Handler Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/api/02-method.md Use `onUpload` to get upload progress information. It returns a function to unbind the event handler. ```typescript const method = alova.Get('/api/upload_file', formData); const offEvent = method.onUpload(event => { console.log('File size:', event.total); console.log('Uploaded:', event.loaded); }); offEvent(); ``` -------------------------------- ### Enable Immediate SSE Request Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/03-client/01-strategy/14-use-sse.md Set `immediate: true` in the `useSSE` options to automatically send the request when the component mounts. Otherwise, you need to call the `send` function manually. ```javascript const { data, eventSource, readyState, onMessage, onError, on, send, close } = useSSE( postMethodHandler, { immediate: true } ); ``` -------------------------------- ### Pass URL Parameters with params Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/02-getting-started/03-basic/03-method.md Use the `params` option to append URL parameters to the request URL. This is useful for GET requests. ```javascript alovaInstance.Get('/todo/list', { params: { userId: 1 } }); ``` -------------------------------- ### Configure Redis Storage Adapter Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/04-server/01-strategy/02-send-captcha.md Sets up the Redis storage adapter for the captcha provider. Ensure Redis is running and accessible with the provided credentials. ```javascript const redisAdapter = new RedisStorageAdapter({ host: 'localhost', port: '6379', username: 'default', password: 'my-top-secret', db: 0 }); createCaptchaProvider({ store: redisAdapter }); ``` -------------------------------- ### Bind Download Progress Handler Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/api/02-method.md Use `onDownload` to get download progress information. It returns a function to unbind the event handler. ```typescript const method = alova.Get('/api/download_file'); const offEvent = method.onDownload(event => { console.log('File size:', event.total); console.log('Downloaded:', event.loaded); }); offEvent(); ``` -------------------------------- ### Data Fetching Strategy Initialization and Usage Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/02-getting-started/01-introduce.md Utilize the Data Fetching strategy to pre-fetch necessary data, improving user experience by avoiding loading delays. Initialize with useFetcher and use the fetch action to request data for specific items. ```javascript const { // Response states loading, error, // Events onSuccess, onError, onComplete, // actions fetch, update, abort // ... } = useFetcher(); const handleItemClick = itemId => { fetch( alova.Get('/ api/user/detail', { params: { id: itemId } }) ); }; ``` -------------------------------- ### Create Alova Instance with Mock Adapter Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/01-request-adapter/01-alova-mock.md Combines mock interfaces from multiple developers and versions into a single mock adapter for the Alova instance. Sets up the HTTP adapter and a delay for mock responses. ```javascript import Augustv1_1 from './August-v1.1'; import Keevenv1_1 from './kevin-v1.1'; const mockAdapter = createAlovaMockAdapter([Augustv1_1, kevinv1_1], { httpAdapter: adapterFetch(), delay: 1000 }); export const alovaInst = createAlova({ baseURL: 'http://xxx', requestAdapter: mockAdapter // ... }); ``` -------------------------------- ### Add Prefix to Tags Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/resource/04-devtool-plugins/02-tag-modifier.md Use the tagModifier plugin to add a specified prefix to all API tags. This example adds the 'api_' prefix. ```javascript // Add "api_" prefix to all tags tagModifier(tag => `api_${tag}`); ``` -------------------------------- ### Reset List and Clear Cache Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/tutorial/03-client/01-strategy/04-use-pagination.md Execute the `reload` function to clear all cached data and reload the list starting from the first page. ```typescript /** * Reload the list from the first page and clear the cache * @returns [v3.1.0+]promise instance, indicating whether the reset is successful */ declare function reload(): Promise; ``` -------------------------------- ### alova.Get() Source: https://github.com/alovajs/alovajs.github.io/blob/main/docs/api/01-alova.md Creates a method instance for a GET request. This method allows specifying the request URL and configuration options such as headers, parameters, caching, and more. ```APIDOC ## alova.Get() Create a method instance for a GET request. ### Method Signature ```ts interface Alova { Get(url: string, config?: AlovaMethodCreateConfig): Method; } ``` ### Parameters 1. **url** (string): The request address. 2. **config** (AlovaMethodCreateConfig): Optional configuration parameters for the request. #### Configuration Parameters * **headers** (object): Request headers. [View details](/tutorial/getting-started/basic/method) * **params** (object): Request parameters. [View details](/tutorial/getting-started/basic/method) * **name** (string): Method object name, used for state updates, cache invalidation, and fetching. [View details](/tutorial/client/in-depth/update-across-components), [View details](/tutorial/cache/manually-invalidate), [View details](/tutorial/cache/set-and-query), [View details](/tutorial/client/strategy/use-fetcher) * **timeout** (number): Request timeout duration. [See details](/tutorial/getting-started/basic/method) * **cacheFor** (cacheForConfig): Response cache duration. [See details](/tutorial/cache/mode) * **hitSource** (string): Hit source method instance. When the source method instance request is successful, the cache of the current method instance will be invalidated. [See details](/tutorial/cache/auto-invalidate) * **transform** (function): Function to convert response data. [View details](/tutorial/getting-started/basic/method) * **shareRequest** (boolean): Request-level shared request switch. [View details](/tutorial/getting-started/basic/method) * **meta** (any): Method metadata. [View details](/tutorial/getting-started/basic/method-metadata) > Note: In addition to the configurable parameters above, other parameters supported by the request adapter are also supported. ### Return - **Method**: A method instance. ### Example ```ts const getUsers = alovaInstance.Get('/users', { params: { id: 1 } // ... }); ``` ```