【问题标题】:NextJS rewrites with wildcard query string paramsNextJS 使用通配符查询字符串参数重写
【发布时间】:2021-11-10 15:18:40
【问题描述】:

我遇到了一点问题:我正在尝试在 NextJS 中设置一个重写,它会自动将查询字符串发送到目的地。但是,我能找到的唯一示例是命名参数。在这种情况下,可能有任意数量的参数,所以我需要一种制作通配符的方法(我认为这可能吗?)

我想做的是:

/results?param1=a&param2=b... => https://www.somedomain.com/results?param1=a&param2=b...
or
/results?house=red&car=blue&money=none => https://www.somedomain.com/results??house=red&car=blue&money=none

rewrites() {
    return [ 
      {
        source:'/results?:params*',
        destination:'https://www.somedomain.com/results?:params*'
      },

当然这不起作用,所以我查看了has,但我无法锻炼如何在没有名称参数的情况下使其工作

       {
          source: '/some-page',
          destination: '/somewhere-else',
          has: [{ type: 'query', key: 'overrideMe' }],
        },

【问题讨论】:

  • 默认情况下,简单的重写将传递源 URL 可能具有的任何查询参数。只需{ source: '/results', destination: 'https://www.somedomain.com/results' }
  • 谢谢,我感觉自己像个十足的叮当。我为什么不尝试呢? :)

标签: next.js query-string nextjs-rewrites


【解决方案1】:

您可以使用如下所示的标准页面。我所做的是当路由器在useEffect 钩子中初始化时,它获取查询(对象),然后使用objectToQueryString 函数将其转换回url 编码字符串,然后使用router 重定向到其他页面

// /pages/some-page.jsx
import { useRouter } from 'next/router'
import { useEffect } from 'react'

const objectToQueryString = (initialObj) => {
    const reducer = (obj, parentPrefix = null) => (prev, key) => {
        const val = obj[key];
        key = encodeURIComponent(key);
        const prefix = parentPrefix ? `${parentPrefix}[${key}]` : key;

        if (val == null || typeof val === 'function') {
            prev.push(`${prefix}=`);
            return prev;
        }

        if (['number', 'boolean', 'string'].includes(typeof val)) {
            prev.push(`${prefix}=${encodeURIComponent(val)}`);
            return prev;
        }

        prev.push(Object.keys(val).reduce(reducer(val, prefix), []).join('&'));
        return prev;
    };

    return Object.keys(initialObj).reduce(reducer(initialObj), []).join('&');
};

const Results = () => {
    const router = useRouter()

    useEffect(() => {
        const query = router.query
        router.replace(`https://www.somedomain.com/results?${objectToQueryString(query)}`)
    }, [router])

    return <></>

}
export default Results

我使用基于Query-string encoding of a Javascript ObjectobjectToQueryString

【讨论】:

  • 我已经做了类似的事情,有点我不想重定向,我是重写 URL,所以这一切都发生在现有域中。不过还是谢谢。
猜你喜欢
  • 2020-03-14
  • 2011-11-16
  • 2016-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-12
相关资源
最近更新 更多