我有一个连接到NodeJS API的Nextjs应用程序。 我的页面上有一个表单,用于向后端API发出POST请求。
向我的API发出POST请求后,我的前端将我重定向到另一个页面。 现在出现了问题,在重定向我后,当我按下后退按钮时,nextJS将我发送到错误页面,该页面显示“发生了意外错误”。
在部署我的应用程序后我意识到了这个错误,这真是一个痛苦。
答案 0 :(得分:1)
目前尚不清楚您如何实现这一目标
向我的API发出POST请求后,我的前端将我重定向到另一个页面。
您是否将router.push('/submitted')
和handleSubmit
函数一起使用?还是您正在使用整页重定向?
这听起来像是整页重定向,如果是的话,您有两个选择
fetch
API,以便您可以对后端进行POST并处理路由内的成功和失败。完成此操作后,您可以选择将用户推送到/success
并处理getserversideprops
中的任何后退行为,因此您可以选择隐藏表单或替换进入首页的路线作为示例-请参见{{ 3}} 例如:
const handleSubmit = async e => {
e.preventDefault();
try {
const res = await fetch('<YOURBACKEND>/submit', {
method: 'POST',
body: JSON.stringify(<YOUR Form Fields>),
headers: { 'Content-Type': 'application/json' }
});
const json = await res.json();
if (json.success) {
setResponse({
type: 'success',
message: 'Thank you for reaching out to us.'
});
// Assume Router is available
router.replace('/home');
} else {
setResponse({
type: 'error',
message: json.message
});
}
} catch (e) {
console.log('An error occurred', e);
setResponse({
type: 'error',
message: 'An error occured while submitting the form'
});
}
};
// Snippet credit : https://medium.com/qualascend/add-a-static-form-to-your-nextjs-app-without-serverside-code-67e10a6ea7b8
res.setHeader('Cache-Control', 's-maxage=60, stale-while-revalidate');
发布有关重定向方式的更多代码。