Axios POST请求成功后无法跳转,响应JSON被渲染为HTML问题
问题解决:Axios POST成功后无法跳转&服务端跳转方案
一、前端代码错误修复(解决跳转失效问题)
你的前端代码存在3个关键错误,直接导致跳转逻辑失效:
- Axios回调执行时机错误
当前写法.then(location.assign('/[newUrl]'))会让location.assign在请求发送前就直接执行,而非等待请求成功后触发。正确写法是将跳转逻辑包装为回调函数:
const creatClient = async (client) => { try { const res = await axios({ method: 'POST', withCredentials: true, url: '/[url]', data: client, }); // 请求成功后再执行跳转 location.assign('/[newUrl]'); } catch (error) { console.log(error); } };
- 未阻止表单默认提交行为
e.preventDefault未加括号,等于没调用该方法,表单会以默认方式提交导致页面刷新,中断Axios异步逻辑:
submitbtn.addEventListener('click', (e) => { e.preventDefault(); // 加括号执行方法 // ... 其他代码 });
- 函数传参错误
creatClient(...client)中,client是对象,展开运算符会把对象键名作为参数传递,而函数期望接收完整对象,应直接传入:
creatClient(client);
修复后的完整前端代码:
const creatClient = async (client) => { try { const res = await axios({ method: 'POST', withCredentials: true, url: '/[url]', data: client, }); location.assign('/[newUrl]'); } catch (error) { console.log(error); } }; submitbtn.addEventListener('click', (e) => { e.preventDefault(); const name = document.getElementById('name').value; const phone = document.getElementById('phone').value; const createdATT = new Date(document.getElementById('date').value); const followUp = new Date(document.getElementById('date2').value); const images = document.getElementById('img').value; const insurance = document.getElementById('insurance').value; const client = { name, phone, insurance, images, createdATT, followUp }; console.log(client); client ? creatClient(client) : console.log('no object created'); });
二、服务端侧的跳转方案
由于你使用Axios异步请求,服务端直接res.redirect()无法触发前端跳转(AJAX请求不会自动处理重定向响应),推荐两种可行方案:
方案1:服务端返回跳转指令,前端接收后执行
修改后端controller,在创建成功后返回包含跳转地址的JSON响应,前端收到后执行跳转:
exports.createClients = async (req, res, next) => { try { if (req.file) req.body.images = req.file.filename; const newClient = await Client.create(req.body); res.status(200).json({ status: 'success', newClient, redirectUrl: '/[newUrl]' // 添加跳转地址 }); } catch (err) { console.log(err); res.status(500).json({ status: 'error', message: err.message }); } };
前端对应修改请求逻辑:
const creatClient = async (client) => { try { const res = await axios({ method: 'POST', withCredentials: true, url: '/[url]', data: client, }); if (res.data.redirectUrl) { location.assign(res.data.redirectUrl); } } catch (error) { console.log(error); } };
方案2:改用普通表单提交(无需Axios)
如果不需要异步处理,直接用HTML表单提交,服务端可直接返回重定向响应:
- 前端HTML表单需设置正确属性(文件上传必须加
enctype):
<form action="/[url]" method="POST" enctype="multipart/form-data"> <!-- 表单字段:name、phone、date等 --> <button type="submit" id="submitbtn">提交</button> </form>
- 后端controller修改为创建成功后直接重定向:
exports.createClients = async (req, res, next) => { try { if (req.file) req.body.images = req.file.filename; await Client.create(req.body); res.redirect('/[newUrl]'); // 直接重定向 } catch (err) { console.log(err); res.status(500).send('创建失败'); } };
内容的提问来源于stack exchange,提问作者nageh
相关产品推荐
相关产品推荐

