当我使用 axios 进行 http 调用时,它会进入 catch 块并出现错误
I think you have multiple choices. You can either extract your code from then
callback into function - and call it in error handler when status code is 300.
You could also try this option from axios, to reject the promise only when the status code is > 301.
axios.get('/user/12345', {
validateStatus: function (status) {
return status <= 300; // Reject only if the status code is greater than 300
}
})
I've needed something a bit more dynamic:
// oversimplified index.js
const axios = require('axios')
const allowedStatusList = json.parse(process.env.ALLOWED_STATUSES) || ["2xx"]
// ^^ check that it's a valid input yourself :p
const validateRequestStatusCode = allowedStatuses => {
const stringStatuses = allowedStatuses.map(String)
return status => {
if (stringStatuses.includes(String(status))) {
return true
} else {
for (let wildCardStatus of stringStatuses) {
const validRange = wildCardStatus.match(/.+?(?=xx)/g)
if (validRange && String(status).substring(0, 1) == validRange[0]) {
return true
}
}
}
return false
}
}
const axiosConfig = {
validateStatus: validateRequestStatusCode(allowedStatusList),
url,
data
// etc
}
axios(axiosConfig)
.then(...)
.catch(...)
This would allow you to just supply an environment variable (or however you want to do your config) to change what statuses are valid.
For example, setting ALLOWED_STATUSES='["2xx", "3xx", "4xx"]'
would allow any status code from 200 and 499. Set ALLOWED_STATUSES='[200, 201, "3xx"]'
and you'd have a far more specific filter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.