【问题标题】:Stop Caching Redirect in NextJS在 NextJS 中停止缓存重定向
【发布时间】:2021-04-18 18:23:28
【问题描述】:

如果我没有找到代码 query 参数,我想将用户重定向到错误页面

import { useEffect } from 'react';
import { useRouter } from 'next/router';

export default function Home(props){
  const router = useRouter();
  useEffect(() =>  {
    if(!props.code){
      console.log('No code found');
      router.push('/error');
    }
  });
  // call an api passing the code
    return (
      <>
        <div>Something</div>
      </>
    )
}

export async function getServerSideProps(context) {
  context.res.setHeader('Cache-Control', 'No-Cache');

  return {
    props: { code: context.query.code || null }
  }
}

如果用户使用 URL localhost:3000/ 访问此页面,则应将其重定向到 localhost:3000/error,但如果用户带有特定查询参数 localhost:3000/?code=1234,则不得重定向用户。

问题是当我测试这个组件去没有code参数的URL时,我正确地重定向到错误页面(localhost:3000/error),但是在这之后,如果我输入urllocalhost:3000/?code=1234,我也重定向到错误页面。

当我在匿名窗口中尝试此操作时,我在转到 localhost:3000/ 后转到 localhost:3000/?code=1234 时被正确重定向(然后转到错误页面)

我怎样才能阻止这种行为?

【问题讨论】:

标签: next.js


【解决方案1】:

我相信您的useEffect 代码应该只在组件安装在浏览器中时运行一次。

  useEffect(() =>  {
    if(!props.code){
      console.log('No code found');
      router.push('/error');
    }
  },[]);

或者,您可以在getServerSideProps 内立即重定向

export const getServerSideProps = async (context) => {
  const { res } =  context;
  // if there is no code do the redirect
  res.writeHead(301, { location: "https://google.com" } );
  res.end();
}

【讨论】:

    【解决方案2】:

    由于您使用的是 getServerSideProps 并且可以访问那里的查询参数,因此您可以直接在服务器端重定向,甚至不必安装 Home 组件。

    export async function getServerSideProps(context) {
        if (!context.query.code) {
            return {
                redirect: {
                    destination: '/error',
                    permanent: false
                }
            }
        }
    
        return {
            props: { code: context.query.code }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-30
      • 1970-01-01
      • 2021-01-04
      • 2017-11-03
      • 1970-01-01
      • 2012-02-26
      • 2012-09-19
      • 1970-01-01
      • 2019-05-13
      相关资源
      最近更新 更多