-
-
Save matthewsuan/2bdc9e7f459d5b073d58d1ebc0613169 to your computer and use it in GitHub Desktop.
| import axios from 'axios' | |
| const MAX_REQUESTS_COUNT = 5 | |
| const INTERVAL_MS = 10 | |
| let PENDING_REQUESTS = 0 | |
| // create new axios instance | |
| const api = axios.create({}) | |
| /** | |
| * Axios Request Interceptor | |
| */ | |
| api.interceptors.request.use(function (config) { | |
| return new Promise((resolve, reject) => { | |
| let interval = setInterval(() => { | |
| if (PENDING_REQUESTS < MAX_REQUESTS_COUNT) { | |
| PENDING_REQUESTS++ | |
| clearInterval(interval) | |
| resolve(config) | |
| } | |
| }, INTERVAL_MS) | |
| }) | |
| }) | |
| /** | |
| * Axios Response Interceptor | |
| */ | |
| api.interceptors.response.use(function (response) { | |
| PENDING_REQUESTS = Math.max(0, PENDING_REQUESTS - 1) | |
| return Promise.resolve(response) | |
| }, function (error) { | |
| PENDING_REQUESTS = Math.max(0, PENDING_REQUESTS - 1) | |
| return Promise.reject(error) | |
| }) | |
| export default api |
instead of importing axios, you can just import this file like so:
import axiosWithDelimiterFile from 'path-to-this-file`
// then use it like a normal axios object
axiosWithDelimiterFile.get(url).then()
Could you explain again how should I import it to laravel project?
In bootstrap.js I have:
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
This is exactly what I was looking for! I was getting too many socket errors with a node app that writes data from a read stream to a remote API with POST calls. Thanks for putting this out there! This helped me rate limit my app so I don't overwhelm the remote API.
Hi , Tried using this axios interceptor for the request only. Limited the MAX_REQUESTS_COUNT=1 and INTERVAL_MS=1000.
I was using it for the axios 429 "too many concurrent request " error. The server takes only 1 request per second.Even the logs are getting generated only 1 time but some how i am getting this error . Can you help.
Thanks.
You are a genius
Thank you so much for this!
How to call this from file containing code axios.get