【问题标题】:How to add a filename extension to an Next.js url?如何将文件扩展名添加到 Next.js url?
【发布时间】:2022-01-25 16:24:41
【问题描述】:

示例:我需要将这个 URL:https://example.com/data/publications 重定向到这个:https://example.com/data/publications.json

我已经尝试过 Next.js 重定向,但我未能添加不以 / 开头的字符串

例如,这不起作用:

  async redirects() {
    return [
      {
        source: '/data/:slug',
        destination: '/data/:slug.json',
        permanent: true,
      },
    ]
  },

在 .json 周围添加 () 没有帮助

【问题讨论】:

  • 这样做的用例是什么?如果您尝试提供静态 JSON 文件,为什么不直接将文件移动到 public 文件夹?

标签: javascript reactjs redirect next.js


【解决方案1】:

使用中间件怎么样?中间件是客户端连接到特定路由时执行的函数。

使用中间件;在“pages/data”文件夹中,创建“_middleware.js”文件并使用下面的代码。此代码检查 url 是否有“json”扩展名。如果没有,则将客户端重定向到带有“json”版本的 url。

import { NextResponse } from 'next/server';

export default function myMiddleware(req, e) {
  if (!req.url.endsWith("json")) return new NextResponse.redirect(`${req.url}.json`);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    相关资源
    最近更新 更多