[英]Status code 300 return error in catch block when using axios
当我使用 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.您可以提取您的代码then
回调到功能-当状态代码为300叫它在错误处理程序。
You could also try this option from axios, to reject the promise only when the status code is > 301.您也可以从 axios 尝试此选项,仅当状态代码 > 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.例如,设置ALLOWED_STATUSES='["2xx", "3xx", "4xx"]'
将允许来自 200 和 499 的任何状态代码。设置ALLOWED_STATUSES='[200, 201, "3xx"]'
并且你有一个更具体的过滤器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.