Comments (18)
I have made a set of extensions for axios, including caching GET request, which depends on axios custom adapter mechanism and lru-cache, and the most important thing is the test coverage has reached 100% 🎉. https://github.com/kuitos/axios-extensions
Example
import axios from 'axios';
import { cacheAdapterEnhancer } from 'axios-extensions';
const http = axios.create({
baseURL: '/',
headers: { 'Cache-Control': 'no-cache' },
// cache will be enabled by default
adapter: cacheAdapterEnhancer(axios.defaults.adapter)
});
http.get('/users'); // make real http request
http.get('/users'); // use the response from the cache of previous request, without real http request made
http.get('/users', { cache: false }); // disable cache manually and the the real http request invoked
btw, I have made another powerful extension, which can throttle the requests in the threshold time.
import axios from 'axios';
import { throttleAdapterEnhancer } from 'axios-extensions';
const http = axios.create({
baseURL: '/',
headers: { 'Cache-Control': 'no-cache' },
adapter: throttleAdapterEnhancer(axios.defaults.adapter, 2 * 1000)
});
http.get('/users'); // make real http request
http.get('/users'); // responsed from the cache
http.get('/users'); // responsed from the cache
for more information u can check the api doc
Hope that can be useful for u and feel free to ask any questions🙂
from axios.
Made a thing for this https://github.com/RasCarlito/axios-cache-adapter :)
I released a first version but it needs more testing. Hope it can be useful for others.
I'm going to implement it in a big project for one of my clients.
By default it uses an in memory custom store for the cache.
In browsers it can receive a Promisified localStorage
instance like localForage
.
I haven't explored for an equivalent solution in Node.
Example:
import axios from 'axios'
import { setupCache } from 'axios-cache-adapter'
const cache = setupCache(/* options */)
const api = axios.create({
adapter: cache.adapter
})
api.get('some-url').then(response => /* Do something awesome with response.data \o/ */)
Cheers 🍻
from axios.
Depending on your use case, you can just override get
function:
// Create intercepting get function which returns cached promise,
// hence multiple requests to the same URL will be resolved by
// a single promise.
function cachingGet (get) {
const cache = new Map()
return function cachedGet (url) {
const key = url
if (cache.has(key)) {
return cache.get(key)
} else {
const request = get(...arguments)
cache.set(key, request)
return request
}
}
}
const instance = axios.create(config)
instance.get = cachingGet(instance.get)
from axios.
Bump... need this or I am going to swap out axios for superagent or request for our production app... causes huge slowdowns
from axios.
To people just want to disable cache I used:
const config = { headers: {'Content-Type': 'application/json','Cache-Control' : 'no-cache'}};
and call my api like this:
const { data } = await axios.get('http://www.youraddress.com/api/data.json', config);
from axios.
I think right now caching can be implemented via interceptors, although it's not very clean:
cache(axios, options);
function cache(instance, options) {
instance.interceptors.request.use(function(config) {
if (!config.method === 'get') {
return config;
}
return cache.get(generateOptions(config, options))
.then(createCachedError, function() { return config; });
});
instance.interceptors.response.use(null, function(error) {
if (error.cachedResult) {
return Promise.resolve(error.cachedResult);
}
return Promise.reject(error);
});
}
A cleaner way to do this could be defining the default adapter (http, xhr) in the instance defaults and then using a custom adapter like this:
axios.get('url', { adapter: cachingAdapter });
function cachingAdapter(resolve, reject, config) {
cache.get(generateOptions(config, options)).then(function(result) {
resolve(createResponse(result));
}, function() {
axios.defaults.adapter(resolve, reject, config);
});
}
I also think that adapters should return promises instead of getting the resolve and reject methods, but that's not an issue right now.
I think Axios should leave caching out of the core and allow an implementation like this.
What do you think?
from axios.
@mzabriskie I've added support for ttls in mzabriskie/felix#4 and can tackle this if you like my implementation there.
from axios.
👍 The node version isn't super useful for me until we have a plugable caching layer.
from axios.
Heh, I was just looking into this! I thought that an interceptor could be used or a transformer that'll immediately resolve with a response, but no such luck yet.
Felix looks interesting for sure...
from axios.
Any progress in browser? The cache working?
from axios.
Glad to see this issue being revived, it would save me from having to write a bunch of boilerplate 😄
from axios.
I'm closing this issue due to inactivity. Feel free to reopen it if you consider it requires further discussion ;)
from axios.
Is there a solution for this? It seems odd that there is no obvious way onto caching requests...
from axios.
@rubennorte what is options in cache(axios, options); ?
from axios.
@john1jan hypothetical options for the cache client you use. For example, options for a catbox client.
from axios.
maybe a better solution would be using adpater pattern ?
from axios.
How about this in TypeScript [can easily be a JS thing] -
export class AxiosFactory {
private static CACHE_MAP = new Map<string, AxiosResponse>();
private static attachTokenToURL(config): AxiosFactory {
let urlToUse = config.url;
// Custom Token Attachment
return config;
}
private static cachingAdapter(config: AxiosRequestConfig): AxiosPromise<AxiosResponse<any>> {
if (!!AxiosFactory.CACHE_MAP.get(config.url)) {
return new Promise((resolve, reject) => {
resolve(AxiosFactory.CACHE_MAP.get(config.url));
});
} else {
return axios.defaults.adapter(config);
}
}
static GetAxiosConfig(baseUrl, enableCaching = false) {
let defaultConfig = {
baseURL: baseUrl,
headers: { "Authorization": TokenService.GetTokenValue() } //optional
} as AxiosRequestConfig;
if (enableCaching) {
defaultConfig.adapter = AxiosFactory.cachingAdapter
}
const instance = axios.create(defaultConfig);
// Only for Adding Tokens in here.
instance.interceptors.request.use((config) => {
config = AxiosFactory.attachTokenToURL(config);
return config;
}, (error) => {
return Promise.reject(error);
});
// Only for catching Caches
instance.interceptors.response.use((response) => {
AxiosFactory.CACHE_MAP.set(response.request.responseURL, response);
return response;
}, (error) => {
return Promise.reject(error);
});
return instance;
}
}
from axios.
const config = { headers: {'Content-Type': 'application/json','Cache-Control' : 'no-cache'}};
Request URL: http://myurl
Referrer Policy: no-referrer-when-downgrade
Provisional headers are shown
Accept: application/json, text/plain, /
ApiKey: myapikey
Cache-Control: no-cache
Referer: http://localhost:3000/orders
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36
it causing issue when request with 'Cache-Control' : 'no-cache' in header .
how can I implement cache-control in my axios instance .
My Code:
const instance = axios.create({baseURL: url});
instance.defaults.headers['ApiKey'] = key;
instance.defaults.headers['Cache-Control'] = "no-cache";
I have also tried your solution passing config in single request . but no luck.
what will be the solution?
from axios.
Related Issues (20)
- whether to use the Fetch API or XHR based on browser support(根据浏览器是否支持fetch API 优先使用fetch来实现请求)
- An error occurred when using the system proxy environment in Linux
- Unable to get the value of Content-Type
- Axios Preventing Constant Contact from running checklist
- Axios request automatically fired a second time after a delay
- Axios sends boundary text even when form data is empty HOT 3
- Progress event does not have lengthComputable property
- test cases fails when the interceptor header exceeds 10 characters
- Form data key of "x-amz-security-token" changes from string key to object {x: { amz: {security: { token: <value> } } } }
- What is the correct version guide of Axios? HOT 2
- SSRF Vulnerability Arising from Axios URL Parsing HOT 3
- Why is the headers attribute of InternalAxiosRequestConfig mandatory?
- Security Vulnerability from follow-redirects HOT 1
- axios V0.28.0 Uncaught ReferenceError: req is not defined at AbortSignal.onCanceled HOT 7
- Network Error in React Native HOT 5
- Axios lib gets detected as a trojan HOT 3
- Can't find variable: axios error thrown on older browser (since v.1.6.8) HOT 1
- Invalid package attestation - 1.6.8 HOT 4
- Axios calculating wrong Content-Length HOT 2
- Information Exposure due to the handling of the Proxy-Authorization header across hosts HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from axios.