Vue结合Laravel调用axios.post请求API返回400时error变量未赋值问题
问题原因
Axios 默认的响应判定逻辑是仅当HTTP状态码属于2xx范围时,才会走.then()回调,400、401、500这类非2xx状态码都会被判定为请求失败,直接进入.catch()回调,你把400的判断逻辑写在.then()里自然不会执行。
修复方案
你可以从下面两种写法里选一种调整:
方案1:统一用async/await + try/catch(更推荐,符合异步语法规范)
async inputschedule(){ try { const response = await axios.post('api/schedule',{ tweet:this.text, schedule_at:this.data+' '+this.clock }) // 此处编写2xx状态对应的处理逻辑 } catch (error) { // 所有非2xx状态、网络异常都会进入catch if (error.response && error.response.status === 400) { console.log(error.response.status) this.error = 'Il post non può essere pianificato per questa data' } } }
方案2:保留Promise链式写法,补充catch回调
async inputschedule(){ await axios.post('api/schedule',{ tweet:this.text, schedule_at:this.data+' '+this.clock }) .then((response)=>{ // 此处编写2xx状态对应的处理逻辑 }) .catch((error)=>{ if (error.response && error.response.status === 400) { console.log(error.response.status) this.error='Il post non può essere pianificato per questa data' } }) }
可选配置
如果需要让指定范围的非2xx状态也进入.then()回调,可以修改axios的validateStatus配置:
await axios.post('api/schedule', { tweet:this.text, schedule_at:this.data+' '+this.clock }, { // 示例配置:只要状态码小于500都判定为请求成功,进入then回调 validateStatus: (status) => status < 500 })
注意:catch逻辑中需要先判断error.response是否存在,避免网络错误、跨域等无响应返回的场景下抛出额外异常。
内容的提问来源于stack exchange,提问作者Marco Carullo
相关产品推荐
相关产品推荐

