gpt4 book ai didi

javascript - 如何在不重新加载页面的情况下将服务器端重定向到其他页面并且仍然将 URL 保留在 Nextjs 应用程序中?

转载 作者:行者123 更新时间:2023-12-03 17:38:17 24 4
gpt4 key购买 nike

我有一个 [slug].js将获取 API 以获取目标页面的页面

export async function getServerSideProps({ query, res }) {
const slug = query.slug;
try {
const destination = await RoutingAPI.matchSlug(slug);
res.writeHead(302, { Location: destination });
res.end();
// return {
// redirect: {
// permanent: true,
// destination,
// },
// }
} catch (error) {
return {
notFound: true
}
}
}
如果我客户端从另一个页面重定向到 slug 页面,它可以工作并保持 URL 与 slug 相同,但它会使浏览器重新加载。如果我使用
return {
redirect: {
permanent: true,
destination,
},
}
它不会重新加载浏览器,但会将 URL 更改为目标,与 slug 不同。我该如何解决这个问题?我会很感激任何想法,谢谢

最佳答案

您可以使用重写来实现此目的。来自 docs :

Rewrites allow you to map an incoming request path to a different destination path.


在您的 next.config.js添加这个:
module.exports = {
async rewrites() {
return [
{
source: "/:slug",
destination: "/your-destination",
},
];
},
};

rewrites is an async function that expects an array to be returned holding objects with source and destination properties:


  • source 是传入的请求路径模式。
  • destination 是您要路由到的路径。
  • 关于javascript - 如何在不重新加载页面的情况下将服务器端重定向到其他页面并且仍然将 URL 保留在 Nextjs 应用程序中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66472986/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com