### Install ofetch Source: https://unjs.io/packages/ofetch Commands to install the ofetch package using npm or yarn. ```bash # npm npm i ofetch # yarn yarn add ofetch ``` -------------------------------- ### Configure Response Parsing Source: https://unjs.io/packages/ofetch Examples of customizing response parsing using specific parsers or forcing response types. ```javascript // Use JSON.parse await ofetch("/movie?lang=en", { parseResponse: JSON.parse }); // Return text as is await ofetch("/movie?lang=en", { parseResponse: (txt) => txt }); // Get the blob version of the response await ofetch("/api/generate-image", { responseType: "blob" }); ``` -------------------------------- ### Parse JSON Response Source: https://unjs.io/packages/ofetch Example of automatically parsing a JSON response from an API endpoint. ```javascript const { users } = await ofetch("/api/users"); ``` -------------------------------- ### ofetch.create Source: https://unjs.io/packages/ofetch Creates a new fetch instance with default options that are inherited by subsequent calls. ```APIDOC ## ofetch.create(options) ### Description Creates a fetch instance with default options. Defaults are cloned at one level. ### Parameters - **options** (object) - Required - Configuration options including baseURL and others. ### Example ```javascript const apiFetch = ofetch.create({ baseURL: "/api" }); apiFetch("/test"); ``` ``` -------------------------------- ### Create fetch with default options Source: https://unjs.io/packages/ofetch Use ofetch.create to define a reusable fetch instance with shared base options. Note that nested options like headers are cloned at one level. ```javascript const apiFetch = ofetch.create({ baseURL: "/api" }); apiFetch("/test"); // Same as ofetch('/test', { baseURL: '/api' }) ``` -------------------------------- ### Using native fetch Source: https://unjs.io/packages/ofetch Access the native fetch API directly via the ofetch.native shortcut. ```javascript const json = await ofetch.native("/sushi").then((r) => r.json()); ``` -------------------------------- ### ofetch.raw Source: https://unjs.io/packages/ofetch Performs a fetch request and returns the raw response object including headers. ```APIDOC ## ofetch.raw(url, options) ### Description Access the raw response object for headers and other response metadata. ### Example ```javascript const response = await ofetch.raw("/sushi"); // response._data // response.headers ``` ``` -------------------------------- ### ofetch.native Source: https://unjs.io/packages/ofetch Provides access to the native fetch API. ```APIDOC ## ofetch.native(url, options) ### Description Shortcut to use the native fetch API. ### Example ```javascript const json = await ofetch.native("/sushi").then((r) => r.json()); ``` ``` -------------------------------- ### Handle Fetch Errors Source: https://unjs.io/packages/ofetch Demonstrates the default error throwing behavior when response.ok is false. ```javascript await ofetch("https://google.com/404"); // FetchError: [GET] "https://google/404": 404 Not Found // at async main (/project/playground.ts:4:3) ``` -------------------------------- ### Import ofetch Source: https://unjs.io/packages/ofetch Syntax for importing ofetch in ESM/TypeScript or CommonJS environments. ```javascript // ESM / Typescript import { ofetch } from "ofetch"; // CommonJS const { ofetch } = require("ofetch"); ``` -------------------------------- ### ofetch(url, options) Source: https://unjs.io/packages/ofetch The primary function for making HTTP requests with support for query parameters. ```APIDOC ## ofetch(url, options) ### Description Performs an HTTP request. Query parameters can be added via the `query` or `params` option, which preserves existing query strings in the URL. ### Parameters - **url** (string) - The request URL. - **options** (object) - Configuration options including `query` or `params`. ### Request Example await ofetch("/movie?lang=en", { query: { id: 123 } }); ``` -------------------------------- ### Prepend baseURL Source: https://unjs.io/packages/ofetch Uses the baseURL option to automatically prefix request paths, handling slashes and query parameters via ufo. ```javascript await ofetch("/config", { baseURL }); ``` -------------------------------- ### Adding HTTP(S) Agent Source: https://unjs.io/packages/ofetch Configure an HTTP(S) agent for Node.js environments using the agent option. ```javascript import { HttpsProxyAgent } from "https-proxy-agent"; await ofetch("/api", { agent: new HttpsProxyAgent("http://example.com"), }); ``` -------------------------------- ### Add Query Search Parameters with ofetch Source: https://unjs.io/packages/ofetch Uses the query option to append search parameters to a URL while preserving existing query strings. ```javascript await ofetch("/movie?lang=en", { query: { id: 123 } }); ``` -------------------------------- ### ofetch(url, options) Source: https://unjs.io/packages/ofetch The primary function for making HTTP requests. It supports automatic JSON stringification for request bodies and automatic header injection for POST, PUT, and PATCH methods. ```APIDOC ## ofetch(url, options) ### Description Performs an HTTP request. Automatically stringifies JSON bodies and sets content-type/accept headers for POST, PUT, and PATCH methods. ### Parameters - **url** (string) - Required - The URL to fetch. - **options** (object) - Optional - Configuration object. - **method** (string) - Optional - HTTP method (e.g., POST, PUT, PATCH). - **body** (object|string) - Optional - The request body to send. - **ignoreResponseError** (boolean) - Optional - If true, bypasses automatic error throwing when response.ok is false. ### Request Example ```javascript const { users } = await ofetch("/api/users", { method: "POST", body: { some: "json" }, }); ``` ### Error Handling - `ofetch` throws a `FetchError` when `response.ok` is false. - The parsed error body is accessible via `error.data`. - Use `.catch((err) => err.data)` to handle error responses. ``` -------------------------------- ### ofetch(url, options) Source: https://unjs.io/packages/ofetch The primary function to perform network requests with configurable options for retries, timeouts, and base URLs. ```APIDOC ## ofetch(url, options) ### Description Performs a network request with support for automatic retries, timeouts, and base URL prepending. ### Parameters - **url** (string) - Required - The URL to fetch. - **options** (object) - Optional - Configuration object. - **retry** (number) - Optional - Number of retries. Defaults to 1 for GET, 0 for others. - **retryDelay** (number) - Optional - Delay between retries in milliseconds. Defaults to 0. - **retryStatusCodes** (array) - Optional - List of status codes that trigger a retry. - **timeout** (number) - Optional - Timeout in milliseconds to abort the request. - **baseURL** (string) - Optional - Base URL to prepend to the request path. ### Request Example ```javascript await ofetch("http://google.com/404", { retry: 3, retryDelay: 500, timeout: 3000 }); ``` ``` -------------------------------- ### Accessing raw response Source: https://unjs.io/packages/ofetch Use ofetch.raw to retrieve the full response object, including headers and other metadata. ```javascript const response = await ofetch.raw("/sushi"); // response._data // response.headers // ... ``` -------------------------------- ### Send JSON Body with ofetch Source: https://unjs.io/packages/ofetch Automatically stringifies objects passed to the body option and sets appropriate content-type headers. ```javascript const { users } = await ofetch("/api/users", { method: "POST", body: { some: "json" }, }); ``` -------------------------------- ### Implement onRequest Interceptor Source: https://unjs.io/packages/ofetch Modifies request options or performs logging immediately before the fetch call is executed. ```javascript await ofetch("/api", { async onRequest({ request, options }) { // Log request console.log("[fetch request]", request, options); // Add `?t=1640125211170` to query search params options.query = options.query || {}; options.query.t = new Date(); }, }); ``` -------------------------------- ### Adding headers to requests Source: https://unjs.io/packages/ofetch Include custom headers in a request by passing a headers object to the options. ```javascript await ofetch("/movies", { headers: { Accept: "application/json", "Cache-Control": "no-cache", }, }); ``` -------------------------------- ### Implement onResponse Interceptor Source: https://unjs.io/packages/ofetch Executes after the fetch call completes and the response body has been parsed. ```javascript await ofetch("/api", { async onResponse({ request, response, options }) { // Log response console.log("[fetch response]", request, response.status, response.body); }, }); ``` -------------------------------- ### Implement onResponseError Interceptor Source: https://unjs.io/packages/ofetch Handles cases where the fetch request completes but the response status indicates an error (response.ok is false). ```javascript await ofetch("/api", { async onResponseError({ request, response, options }) { console.log( "[fetch response error]", request, response.status, response.body ); }, }); ``` -------------------------------- ### Configure Request Retries Source: https://unjs.io/packages/ofetch Sets the number of retry attempts and the delay between them for failed requests. ```javascript await ofetch("http://google.com/404", { retry: 3, retryDelay: 500, // ms }); ``` -------------------------------- ### Apply TypeScript Generics Source: https://unjs.io/packages/ofetch Enables type assistance for the response object by passing a generic type to the ofetch call. ```typescript const article = await ofetch
(`/api/article/${id}`); // Auto complete working with article.id ``` -------------------------------- ### Interceptors Source: https://unjs.io/packages/ofetch Lifecycle hooks to intercept and modify requests or handle responses and errors. ```APIDOC ## Interceptors ### onRequest({ request, options }) Called when the request is initiated. Allows modification of options or logging. ### onRequestError({ request, options, error }) Called when the fetch request fails. ### onResponse({ request, options, response }) Called after the fetch call and body parsing. ### onResponseError({ request, options, response }) Called when the fetch call completes but the response is not successful (response.ok is false). ``` -------------------------------- ### Set Request Timeout Source: https://unjs.io/packages/ofetch Defines a duration in milliseconds after which the request will be automatically aborted. ```javascript await ofetch("http://google.com/404", { timeout: 3000, // Timeout after 3 seconds }); ``` -------------------------------- ### Implement onRequestError Interceptor Source: https://unjs.io/packages/ofetch Handles errors that occur during the initiation of the fetch request. ```javascript await ofetch("/api", { async onRequestError({ request, options, error }) { // Log error console.log("[fetch request error]", request, error); }, }); ``` -------------------------------- ### Bypass Status Error Catching Source: https://unjs.io/packages/ofetch Disables automatic error throwing for non-ok status codes using the ignoreResponseError option. ```javascript await ofetch("/url", { ignoreResponseError: true }); ``` -------------------------------- ### Catch Error Response Data Source: https://unjs.io/packages/ofetch Accesses the parsed error body via the error object's data property. ```javascript await ofetch("/url").catch((err) => err.data); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.