通过 Reactjs 中的 axios 取消我的 POST 请求
Canceling my promises a POST Request through axios in Reactjs
我曾经post请求获取数据,因为我想通过发送一些过滤器从服务器获取数据。
如何取消我的承诺通过 Reactjs 中的 onClick 按钮获取数据?
当我们有多个参数来过滤数据时,使用 HTTP post 方法对 select 数据是否正确?
我找到了地址,但没用:
const CancelToken = axios.CancelToken;
let cancel;
function handleProductSearch() {
var newModel=searchProductFilter;
const token = localStorage.token;
if (token) {
// Cancel previous request
if (cancel !== undefined) {
cancel();
setLoadingListResSrch(false)
}
axios.post(baseUrl + 'Basic/ProductSearch', newModel, {
cancelToken: new CancelToken(function executor(c) {
cancel = c;
}),
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'Authorization': `Bearer ${token}`
},
credentials: 'same-origin',
}) .then(response => {
setLoadingListResSrch(false)
if (response.data.length === 0) {
setGoodListResSrch(response.data.result);
}
}) .catch(error => {
setLoadingListResSrch(false)
debugger;
if (axios.isCancel(error)) {
console.log("post Request canceled");
return;
} return;
});
}
}
并且我希望当用户点击新按钮时取消先前的请求。
<FormGroup className="mb-2 ml-sm-2 mb-sm-2">
<div color="seccess" size="sm" className="btn btn-info m-3"
onClick={handleAbrotProductSearch}>
new search</div>
</FormGroup>
const handleAbrotProductSearch = useCallback(() => {
handleProductSearch());
}, [handleProductSearch]);
如果您使用 axios,这可以通过使用取消令牌来完成:
axios.isCancel(thrown)
https://blog.logrocket.com/how-to-make-http-requests-like-a-pro-with-axios/
const source = axios.CancelToken.source();
axios.get('https://media.giphy.com/media/C6JQPEUsZUyVq/giphy.gif', {
cancelToken: source.token
}).catch(thrown => {
if (axios.isCancel(thrown)) {
console.log(thrown.message);
} else {
// handle error
}
});
// cancel the request (the message parameter is optional)
source.cancel('Request canceled.');
使用 HTTP post 方法是正确的,因为您正在使用正文发送过滤器。
您可以取消和中止。
两种情况我都给出了例子。
取消:
const CancelToken = axios.CancelToken;
let cancelPost;
axios.post('/MyReallySlowReport', {
name: 'new name'
}, {
cancelToken: new CancelToken(function executor(c) {
cancelPost = c;
})
})
// cancel the request
cancelPost();
//back end mvc c# example
public async Task<ActionResult> MyReallySlowReport(CancellationToken cancellationToken)
{
CancellationToken disconnectedToken = Response.ClientDisconnectedToken;
var source = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, disconnectedToken);
List<ReportItem> items;
using (ApplicationDbContext context = new ApplicationDbContext())
{
items = await context.ReportItems.ToListAsync(source.Token);
}
return View(items);
}
对于中止:
var xhr = $.ajax({
method: "POST",
url: "/MyReallySlowReport",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
// abort the request
xhr.abort();
是的,可以使用 POST 发送过滤器,如果您使用的是 Fetch API,则只需使用 AbortController
对象即可取消获取请求。
const controller = new AbortController();
fetch(url, { signal: controller.signal })
.then(response => {
console.log(`Complete!`);
}).catch(e => {
console.error(`Error!: ${e.message}`);
});
// call abort to cancel the fetch request
const cancelRequest = () => {
controller.abort();
}
我曾经post请求获取数据,因为我想通过发送一些过滤器从服务器获取数据。
如何取消我的承诺通过 Reactjs 中的 onClick 按钮获取数据?
当我们有多个参数来过滤数据时,使用 HTTP post 方法对 select 数据是否正确?
我找到了地址,但没用:
const CancelToken = axios.CancelToken;
let cancel;
function handleProductSearch() {
var newModel=searchProductFilter;
const token = localStorage.token;
if (token) {
// Cancel previous request
if (cancel !== undefined) {
cancel();
setLoadingListResSrch(false)
}
axios.post(baseUrl + 'Basic/ProductSearch', newModel, {
cancelToken: new CancelToken(function executor(c) {
cancel = c;
}),
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'Authorization': `Bearer ${token}`
},
credentials: 'same-origin',
}) .then(response => {
setLoadingListResSrch(false)
if (response.data.length === 0) {
setGoodListResSrch(response.data.result);
}
}) .catch(error => {
setLoadingListResSrch(false)
debugger;
if (axios.isCancel(error)) {
console.log("post Request canceled");
return;
} return;
});
}
}
并且我希望当用户点击新按钮时取消先前的请求。
<FormGroup className="mb-2 ml-sm-2 mb-sm-2">
<div color="seccess" size="sm" className="btn btn-info m-3"
onClick={handleAbrotProductSearch}>
new search</div>
</FormGroup>
const handleAbrotProductSearch = useCallback(() => {
handleProductSearch());
}, [handleProductSearch]);
如果您使用 axios,这可以通过使用取消令牌来完成:
axios.isCancel(thrown)
https://blog.logrocket.com/how-to-make-http-requests-like-a-pro-with-axios/
const source = axios.CancelToken.source();
axios.get('https://media.giphy.com/media/C6JQPEUsZUyVq/giphy.gif', {
cancelToken: source.token
}).catch(thrown => {
if (axios.isCancel(thrown)) {
console.log(thrown.message);
} else {
// handle error
}
});
// cancel the request (the message parameter is optional)
source.cancel('Request canceled.');
使用 HTTP post 方法是正确的,因为您正在使用正文发送过滤器。
您可以取消和中止。
两种情况我都给出了例子。
取消:
const CancelToken = axios.CancelToken;
let cancelPost;
axios.post('/MyReallySlowReport', {
name: 'new name'
}, {
cancelToken: new CancelToken(function executor(c) {
cancelPost = c;
})
})
// cancel the request
cancelPost();
//back end mvc c# example
public async Task<ActionResult> MyReallySlowReport(CancellationToken cancellationToken)
{
CancellationToken disconnectedToken = Response.ClientDisconnectedToken;
var source = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, disconnectedToken);
List<ReportItem> items;
using (ApplicationDbContext context = new ApplicationDbContext())
{
items = await context.ReportItems.ToListAsync(source.Token);
}
return View(items);
}
对于中止:
var xhr = $.ajax({
method: "POST",
url: "/MyReallySlowReport",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
// abort the request
xhr.abort();
是的,可以使用 POST 发送过滤器,如果您使用的是 Fetch API,则只需使用 AbortController
对象即可取消获取请求。
const controller = new AbortController();
fetch(url, { signal: controller.signal })
.then(response => {
console.log(`Complete!`);
}).catch(e => {
console.error(`Error!: ${e.message}`);
});
// call abort to cancel the fetch request
const cancelRequest = () => {
controller.abort();
}