问题
I use axios
for ajax requests and reactJS
+ flux
for render UI. In my app there is third side timeline (reactJS component). Timeline can be managed by mouse's scroll. App sends ajax request for the actual data after any scroll event. Problem that processing of request at server can be more slow than next scroll event. In this case app can have several (2-3 usually) requests that already is deprecated because user scrolls further. it is a problem because every time at receiving of new data timeline begins redraw. (Because it's reactJS + flux) Because of this, the user sees the movement of the timeline back and forth several times. The easiest way to solve this problem, it just abort previous ajax request as in jQuery
. For example:
$(document).ready(
var xhr;
var fn = function(){
if(xhr && xhr.readyState != 4){
xhr.abort();
}
xhr = $.ajax({
url: 'ajax/progress.ftl',
success: function(data) {
//do something
}
});
};
var interval = setInterval(fn, 500);
);
How to cancel/abort requests in axios
?
回答1:
Axios does not support canceling requests at the moment. Please see this issue for details.
UPDATE: Cancellation support was added in axios v0.15.
回答2:
There is really nice package with few examples of usage called axios-cancel. I've found it very helpful. Here is the link: https://www.npmjs.com/package/axios-cancel
回答3:
This is how I did it using promises in node. Pollings stop after making the first request.
var axios = require('axios');
var CancelToken = axios.CancelToken;
var cancel;
axios.get('www.url.com',
{
cancelToken: new CancelToken(
function executor(c) {
cancel = c;
})
}
).then((response) =>{
cancel();
})
回答4:
import React, { Component } from 'react';
import axios from 'axios';
const CancelToken = axios.CancelToken;
let cancel;
class abc extends Component {
componentDidMount() {
this.Api();
}
Api(){
if (cancel !== undefined) {
cancel();
}
axios.post(URL,reqBody,{cancelToken: new CancelToken(function executor(c)
{
cancel = c;
})
}).then((response) => {
//responce Body
}).catch((error) => {
if (axios.isCancel(error)) {
console.log('post Request canceled');
}
});
}
render() {
return <h2>cancel Axios Request</h2>;
}
}
export default abc;
回答5:
https://github.com/axios/axios#cancellation
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
let url = 'www.url.com'
axios.get(url, {
progress: false,
cancelToken: source.token
})
.then(resp => {
alert('done')
})
setTimeout(() => {
source.cancel('Operation canceled by the user.');
},'1000')
来源:https://stackoverflow.com/questions/38329209/how-to-cancel-abort-ajax-request-in-axios