在GetServerSideProps中重定向时如何传递告警到跳转目标页面?
实现方案
有两种常用的实现方式,可根据你的业务场景选择:
方案1:URL查询参数传递(最简便)
直接把告警信息编码后加到跳转路径的查询参数里,目标页面直接读取参数展示即可。
调整重定向代码
try { const user = await Auth.currentAuthenticatedUser(); } catch (err) { // 对告警内容做URL编码,避免特殊字符报错 const alertMsg = encodeURIComponent('访问受限,请先登录账号后再尝试操作') res.writeHead(302, { Location: `/contests/0/error?alert=${alertMsg}`, }); res.end(); }
目标页面读取参数
以Next.js页面为例,通过路由对象读取参数展示:
import { useRouter } from 'next/router' export default function ErrorPage() { const router = useRouter() const alertMsg = router.query.alert return ( <div> {/* 展示告警提示 */} {alertMsg && <div className="alert-notice">{decodeURIComponent(alertMsg)}</div>} {/* 页面其他内容 */} </div> ) }
该方案的优势是实现简单无额外依赖,适合非敏感的普通提示场景。
方案2:临时Cookie传递(不暴露在URL)
如果不想让告警信息出现在URL里,也可以用临时Cookie存储提示,跳转后读取完立即清除。
调整重定向代码
try { const user = await Auth.currentAuthenticatedUser(); } catch (err) { res.writeHead(302, { Location: "/contests/0/error", // 设置有效期10秒的临时Cookie,足够跳转后读取 "Set-Cookie": `alert_msg=${encodeURIComponent('访问受限,请先登录账号后再尝试操作')}; Path=/; Max-Age=10; HttpOnly=false` }); res.end(); }
目标页面读取并清除Cookie
在目标页面的getServerSideProps中读取Cookie内容,返回给页面同时清除Cookie:
export async function getServerSideProps(context) { const alertMsg = context.req.cookies.alert_msg ? decodeURIComponent(context.req.cookies.alert_msg) : null // 立即清除Cookie,避免重复展示 context.res.setHeader('Set-Cookie', 'alert_msg=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT') return { props: { alertMsg } } } // 页面组件直接通过props拿到告警内容展示即可 export default function ErrorPage({ alertMsg }) { return ( <div> {alertMsg && <div className="alert-notice">{alertMsg}</div>} {/* 页面其他内容 */} </div> ) }
内容的提问来源于stack exchange,提问作者Patrick Yen
相关产品推荐
相关产品推荐

