【问题标题】:why toUpperCase not working in nextjs while adding slug为什么在添加 slug 时 toUpperCase 在 nextjs 中不起作用
【发布时间】:2021-09-21 17:21:09
【问题描述】:

我正在关注此链接 https://nextjs.org/docs/api-reference/next.config.js/headers

添加x-slug键。我是这样添加的

module.exports = {
  async headers() {
    return [
      {
        source: '/:slug',
        headers: [
          {
            key: 'x-slug',
            value: `${abc(':slug')}` // Matched parameters can be used in the value
          }
        ]
      }
    ];
  }
};

当我使用这个网址时 https://nextjs-vetexh--3000.local.webcontainer.io/dsd “蛞蝓”---> dsd

但是当我使用toUppercase() 函数时它不起作用,为什么

function abc(a) {
  // working
 // return a;
 // not working
  return a.toUpperCase();
}

SLUG 大写。

预期输出为“DSD”

这是我的代码 https://stackblitz.com/edit/nextjs-vetexh?file=next.config.js

function abc(a) {
  // working
  // return a;
  // not working
  return a.toUpperCase();
}
module.exports = {
  async headers() {
    return [
      {
        source: '/:slug',
        headers: [
          {
            key: 'x-slug',
            value: `${abc(':slug')}` // Matched parameters can be used in the value
          }
        ]
      }
    ];
  }
};

【问题讨论】:

  • abc函数从何而来?大概是value: ":SLUG" 断开了指向/:slug 的链接,因为在实际发出请求时,该对象没有被评估。
  • 有什么想法可以改成大写吗?预期的输出是“DSD”它给:SLUG
  • 鉴于您的示例显示,您可能不能。除非您可以在下游插入一些中间件,否则一旦设置了实际值,如果存在,则将该标头大写。 value 在该对象中是一个模板,您将其大写而不是实际值。
  • @PsyGik 是的,我确实阅读了链接的文档,我的意思是我不明白您为什么希望将实际值大写。

标签: javascript reactjs next.js


【解决方案1】:

这在next.config.js 中可能是不可能的,但还有其他选项需要一些权衡。

getServerSideProps

您可以通过在_app.js 中使用getServerSideProps 匹配请求的路径来添加自定义HTTP 标头:

export async function getServerSideProps(context) {

  // set HTTP header
  context.res.setHeader('x-slug', upperCase(context.params.slug))

  return {
    props: {}, // will be passed to the page component as props
  }
}

context 参数是一个包含以下键的对象:

  • params:如果此页面使用动态路由,params 包含路由参数。如果页面名称是 [id].js ,则参数看起来像 { id: ... }
  • req:HTTP IncomingMessage 对象。
  • res:HTTP 响应对象。
  • query:表示查询字符串的对象。

但是使用getServerSideProps 会禁用静态优化,因为所有页面都只会在服务器端呈现。

More on Server-side Rendering

使用自定义服务器

另一种方法是使用Custom Server 并覆盖响应标头。


server.get('/:slug*', (req, res) => {
    res.set('x-slug', upperCase(req.params['slug']));
    handle(req, res, parsedUrl);
  });

自定义服务器将移除重要的性能优化,例如无服务器功能和自动静态优化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 2020-10-17
    • 2020-04-17
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多