NextJS 特殊字符路由在浏览器中不起作用

Tha*_*yen 3 next.js

使用 NextJS,我getStaticPaths通过 API 调用来定义一些路由:

/**
 * @dev Fetches the article route and exports the title and id to define the available routes
 */
const getAllArticles = async () => {
    const result = await fetch("https://some_api_url");
    const articles = await result.json();

    return articles.results.map((article) => {
        const articleTitle = `${article.title}`;

        return {
            params: {
                title: articleName,
                id: `${article.id}`,
            },
        };
    });
};

/**
 * @dev Defines the paths available to reach directly
 */
export async function getStaticPaths() {
    const paths = await getAllArticles();
    return {
        paths,
        fallback: false,
    };
}
Run Code Online (Sandbox Code Playgroud)

大部分时间一切正常:我可以访问大部分文章,Router.push适用于定义的所有 URL。

但是,当文章名称包含特殊字符(例如 , )时&Router.push它会继续工作,但从应用程序内部复制/粘贴有效的 URL 到另一个选项卡会返回一个页面:

发生意外的错误。

在检查器的“网络”选项卡中,404出现获取请求错误(在网络中)。

组件代码主要由 API 调用组成,例如:

await API.put(`/set_article/${article.id}`, { object });
Run Code Online (Sandbox Code Playgroud)

API 由 axios 定义。

知道为什么会发生这种情况以及如何制作getStaticPaths具有特殊角色的作品吗?

Tom*_*lak 5

当您在 URL 中传输值时,需要对它们进行 URL 编码。(当您在 HTML 中传输值时,它们需要进行 HTML 编码。在 JSON 中,它们需要进行 JSON 编码。等等。任何可以传输结构化数据的基于文本的系统都有一个您需要应用的编码方案数据。URL 也不例外。)

将原始值转化为客户端代码

await API.put(`/set_article/${article.id}`)
Run Code Online (Sandbox Code Playgroud)

转化为编码的

await API.put(`/set_article/${encodeURIComponent(article.id)}`)
Run Code Online (Sandbox Code Playgroud)

这可能很诱人,但不要在服务器端对值进行预编码。当您实际在 URL 中使用它们时,请在客户端执行此操作。