Nuxt.js与Laravel中Inertia请求303状态的响应检测问题
解决思路:Inertia请求Laravel返回303时无法触发onSuccess重置loading状态
思路1:修改Laravel控制器返回200响应(推荐)
Inertia作为SPA框架,更适配JSON响应或无内容响应,而非传统重定向。将控制器的重定向逻辑改为返回200状态的响应,同时传递提示信息:
public function approve($id) { $lenderMarketLocation = $this->fetchLenderMarketLocation($id); if ($this->canBeApproved($lenderMarketLocation)) { $this->approveMarketLocation($lenderMarketLocation); $this->sendApprovalNotification($lenderMarketLocation); $this->saveLenderMarketLocation($lenderMarketLocation); } $message = 'Market location approved.'; // 方案A:返回JSON响应,前端可直接获取message return response()->json(['message' => $message], 200); // 方案B:用Inertia闪存消息,保留页面状态同时传递提示 session()->flash('message', $message); return response()->noContent(); // 返回204无内容状态,同样触发onSuccess }
修改后前端onSuccess回调会正常触发,loading状态也能顺利重置。
思路2:用Inertia的onFinish回调兜底
Inertia提供的onFinish回调会在请求结束后执行,无论响应是成功、重定向还是错误。直接在请求配置中添加该回调,确保loading状态一定会被重置:
approve(marketLocation) { this.loading = true; this.$inertia.patch( this.$route("admin.marketLocation.approve", { id: marketLocation.id }), { preserveState: true, onSuccess: (response) => { console.log("Success:", response); this.loading = false; }, onError: (error) => { console.log("Error:", error); this.loading = false; }, // 兜底逻辑:无论请求结果如何,最终执行 onFinish: () => { this.loading = false; } } ); },
这个方法无需修改后端,适合快速解决问题,但无法区分请求是否真的成功,若需根据响应做后续逻辑,需额外添加判断。
思路3:配置Inertia识别303为成功状态
若必须保留后端重定向逻辑,可修改Inertia的成功状态码范围,让它把303视为成功状态:
在Nuxt配置文件nuxt.config.js中添加自定义配置:
export default { inertia: { successStatusCodes: [200, 303] // 扩展成功状态码包含303 } }
若上述配置不生效,可通过Inertia响应拦截器手动处理303状态:
// 在plugins/inertia.js中添加拦截逻辑 export default ({ app }) => { app.$inertia.interceptors.response.use( response => { if (response.status === 303) { // 可根据需求触发组件的onSuccess逻辑,或直接重置loading console.log("Redirect handled as success"); } return response; }, error => Promise.reject(error) ); }
内容的提问来源于stack exchange,提问作者Unswaa20
相关产品推荐
相关产品推荐

