React代码状态码500时未显示错误的技术问题求助
问题原因及解决办法
你的代码里,当后端返回500状态码时,axios会直接触发catch块,根本不会执行你写的res.data.status === 500分支逻辑。这是因为axios默认将HTTP状态码≥400的响应判定为请求错误,直接跳转到catch处理。
另外注意:headers里的multipart/formData拼写错误,正确格式是multipart/form-data,这个问题可能导致请求本身异常,建议先修正。
解决方式一:修改axios的错误判定规则
给axios请求添加validateStatus配置,让它不把500状态码视为错误,这样所有状态码的响应都会进入then块,你就能正常判断状态码了:
try { const res = await axios({ method: "post", url: `${landslide}`, data: formData, headers: {'Content-type': "multipart/form-data"}, // 配置:允许所有状态码进入then块自行处理 validateStatus: (status) => true }); console.log("hello", res); if (res.data.status === 200) { swal("success", res.data.message, "success").then(function() { navigation("/landslide"); }); } else if (res.data.status === 500) { swal("warning", res.data.message, "warning").then(function() { navigation("/landslide"); }); } } catch (error) { swal("warning", "please check your form's input", "warning").then(function() { navigation("/landslide-report"); }); }
解决方式二:在catch块中处理500状态码
如果不想修改axios默认规则,可以在catch块里读取error.response获取后端返回的详细信息,判断状态码后针对性处理:
try { const res = await axios({ method: "post", url: `${landslide}`, data: formData, headers: {'Content-type': "multipart/form-data"} }); console.log("hello", res); if (res.data.status === 200) { swal("success", res.data.message, "success").then(function() { navigation("/landslide"); }); } } catch (error) { // 优先处理后端返回的500错误 if (error.response?.data?.status === 500) { swal("warning", error.response.data.message, "warning").then(function() { navigation("/landslide"); }); } else { // 处理其他请求异常 swal("warning", "please check your form's input", "warning").then(function() { navigation("/landslide-report"); }); } }
内容的提问来源于stack exchange,提问作者Priyanka Shakya
相关产品推荐
相关产品推荐

