什么是Axios Cancel Token?取消PUT上传请求的相关疑问
Hey there! Let me break down Axios Cancel Tokens for you in plain terms—this is something I’ve tinkered with a lot when handling aborted uploads and requests.
Think of it as a unique "stop signal" tag tied to a specific request. It’s not just a random flag; it’s a dedicated identifier that lets Axios know exactly which request you want to cancel when the time comes.
Imagine you’ve got 3 uploads running at the same time on a page. If you tried to cancel a request without a token, Axios wouldn’t know which one to stop—you might accidentally kill all of them! The token acts like a name tag: you assign it to one request, so when you trigger a cancel, only the request with that tag gets terminated. No mix-ups, no unintended side effects.
Here’s the step-by-step in plain language:
- First, you create a cancel token pair: a token itself, and a
cancelfunction that’s linked to it. Think of this as making a custom "stop button" for your request. - Next, you attach this token to the PUT (or any) request you’re sending. This tells Axios: "If someone uses the linked cancel function, this is the request to shut down."
- When you need to cancel (like when the user clicks a "Cancel Upload" button), you call that
cancelfunction—you can even add a message explaining why it was canceled (e.g., "User aborted upload"). - Axios picks up the signal, finds the request tied to that token, immediately stops it, and triggers the request’s
catchblock. You can then handle the cancellation there (like showing a notification to the user).
There are two common ways to implement this:
1. Using CancelToken.source() (Most straightforward)
// Step 1: Create the token and cancel function const CancelToken = axios.CancelToken; const source = CancelToken.source(); // Step 2: Send your PUT request with the token attached axios.put('/upload/your-file', yourFormData, { cancelToken: source.token }) .then(response => { console.log('Upload successful!', response); }) .catch(error => { // Check if the error is a cancellation if (axios.isCancel(error)) { console.log('Request canceled:', error.message); } else { // Handle other upload errors console.error('Upload failed:', error); } }); // Step 3: Cancel the request (call this when needed, e.g., button click) source.cancel('User manually canceled the upload');
2. Using the CancelToken Constructor (More flexible for custom scenarios)
If you need more control over when the cancel function is stored or accessed, you can use the constructor approach:
const CancelToken = axios.CancelToken; let cancelRequest; // Attach the token when sending the request axios.put('/upload/your-file', yourFormData, { cancelToken: new CancelToken(function executor(c) { // Store the cancel function to use later cancelRequest = c; }) }); // Cancel the request whenever you need to cancelRequest('Upload canceled due to user action');
内容的提问来源于stack exchange,提问作者cocoPuffs

