Creating a small layer to communicate to your API:
// api/usersimport { mande } from 'mande'const users = mande('/api/users', usersApiOptions)export function getUserById(id) { return users.get(id)}export function createUser(userData) { return users.post(userData)}
Adding Authorization tokens:
// api/usersimport { mande } from 'mande'const todos = mande('/api/todos', todosApiOptions)export function setToken(token) { // todos.options will be used for all requests todos.options.headers.Authorization = 'Bearer ' + token}export function clearToken() { delete todos.options.headers.Authorization}export function createTodo(todoData) { return todo.post(todoData)}
// In a different file, setting the token whenever the login status changes. This depends on your frontend code, for instance, some libraries like Firebase provide this kind of callback but you could use a watcher on Vue.onAuthChange((user) => { if (user) setToken(user.token) else clearToken()})
You can also globally add default options to all mande instances:
import { defaults } from 'mande'defaults.headers.Authorization = 'Bearer token'
To delete a header, pass null to the mande instance or the request:
const legacy = mande('/api/v1/data', { headers: { // override all requests 'Content-Type': 'application/xml', },})// override only this requestlegacy.post(new FormData(), { headers: { // overrides Accept: 'application/json' only for this request Accept: null, 'Content-Type': null, },})
TypeScript
All methods defined on a mande instance accept a type generic to type their return:
const todos = mande('/api/todos', globalOptions)todos.get<{ text: string; id: number; isFinished: boolean }[]>().then((todos) => { // todos is correctly typed})
SSR (and Nuxt in Universal mode)
To make Mande work on Server, make sure to provide a fetch polyfill and to use full URLs and not absolute URLs starting with /. For example, using node-fetch, you can do:
export const BASE_URL = process.server ? process.env.NODE_ENV !== 'production' ? 'http://localhost:3000' : 'https://example.com' : // on client, do not add the domain, so urls end up like `/api/something` ''const fetchPolyfill = process.server ? require('node-fetch') : fetchconst contents = mande(BASE_URL + '/api', {}, fetchPolyfill)
Nuxt 2
Note: If you are doing SSR with authentication, Nuxt 3 hasn't been adapted yet. See #308.
When using with Nuxt and SSR, you must wrap exported functions so they automatically proxy cookies and headers on the server:
When passing Form Data, mande automatically removes the Content-Type header but you can manually set it if needed:
// directly pass it to the mande instanceconst api = mande('/api/', { headers: { 'Content-Type': null } })// or when creating the requestconst formData = new FormData()api.post(formData, { headers: { 'Content-Type': 'multipart/form-data' },})
Most of the time you should let the browser set it for you.
Related
fetchival: part of the code was borrowed from it and the api is very similar