vue-resource中$http请求的成功判定规则是什么?
How vue-resource picks success vs. error callbacks for your POST request
Awesome question—let’s break this down clearly, since it’s all tied to HTTP standards and vue-resource’s built-in logic.
First, the core rule:
- HTTP status codes are the main driver
vue-resource’s promise will fire the success callback when the server sends back an HTTP status code in the 2xx range (200 OK, 201 Created, 204 No Content, etc.). Any status code outside this range—like 400 Bad Request, 404 Not Found, or 500 Internal Server Error—will trigger the error callback instead.
And yes, the response object has a direct property that confirms this:
- Check
response.okfor a boolean indicator
The response object includes anokproperty that’strueif the status code was in the 2xx range (success callback ran), andfalseotherwise (error callback ran). This is a quick way to verify the request’s outcome inside either callback.
Let’s map this to your exact code snippet:
this.$http.post('/someUrl', formData).then( // Success callback: triggers ONLY for 2xx status codes response => { console.log('Request worked!', response.ok); // Logs "true" console.log('Status code:', response.status); // e.g., 200 }, // Error callback: triggers for non-2xx status codes OR network failures response => { console.log('Request failed!', response.ok); // Logs "false" console.log('Issue status code:', response.status); // e.g., 404 or 500 } );
One edge case to note: If the request fails entirely at the network level (like no internet, or the server is totally unreachable), the error callback will still run. In these cases, the response object might have a statusText property explaining the network issue (e.g., "Network Error").
内容的提问来源于stack exchange,提问作者deterjan
相关产品推荐
相关产品推荐

