This is a very light (<2Ko) alternative to Axios when using VueJS and/or Laravel in API mode (appliction/json header).
This library is based on the native javascript Fetch function.
import { fetchApi } from "@ncisrc/fetchApi";
const page = await fetchApi.get('https://www.google.com');
const reply = await fetchApi.post('http://my.api.com/', {
data: 'hello world !'
});
fetchApi can automaticaly set a Bearer Token if your token is stored in a secure cookie in your browser.
The default cookie name is _appToken
You can customize the cookie name by setting one of these environement variable in your .env file :
VUE_APP_TOKEN_COOKIE_NAME
: For VueJS projectsVITE_TOKEN_COOKIE_NAME
: For ViteJS projectsMIX_TOKEN_COOKIE_NAME
: For Laravel Mix projects
Take care to correctly (and securely) set your cookie (Secure Flag, SameSite, check your CORS, etc.).
You can use https://github.com/ncisrc/cookies-storage if you want a simple library to set secure cookies in your JS frontend.
fetchApi can upload files using the upload
method:
index.html
...
<input id="inputFile" type="file" />
<button onClick="upload()">
...
script.js
import fetchApi from '@ncisrv/fetchApi'
async function upload() {
const inputElt = document.getElementById('inputFile');
return await fetchApi.upload('/upload', inputElt);
}
Most of time, you want to redirect your users to the login page/component if fetchApi get a !response.ok
or an HTTP 40X
error code.
You can acheive this by adding you fail handler, return true
if you want to continue the fetchApi flow, false
if you want to stop everything after you failHandler :
fetchApi.failHandler((response) => {
// Your tests on the FETCH response object
// Your redirects
return true; // true : continue, false : stop
});
Example :
fetchApi.failHandler((response) => {
const unauthentified = (response.status > 399 && response.status <500)
if (unauthentified)
window.location = '/login'
return !unauthentified;
})
You can set the bearer token manually by using the setBearerToken
method :
Example :
fetchApi.setBearerToken('myToken');