【发布时间】:2021-05-10 00:04:17
【问题描述】:
我正在尝试使用 REGEXP 帮助使用路径在反应应用程序中呈现 404 页面。我想不通。
这是我想要的正则表达式;我想匹配 IF:
- 整个路径是 !== '/' && 不包含单词 'article'。
编辑:包括澄清代码:
<Switch location={location} key={location.pathname}>
<Route path={["/commentisfree/article/:id", "/commentisfree"]}>
<Opinion />
</Route>
<Route path={["/sport/article/:id", "/sport"]}>
<Sport />
</Route>
<Route path={["/culture/article/:id", "/culture"]}>
<Culture />
</Route>
<Route path={["/lifestyle/article/:id", "/lifestyle"]}>
<Lifestyle />
</Route>
<Route path={["/signup", "/login"]}>
<Account />
</Route>
<Route path={["search/:search", "/search"]}>
<Search />
</Route>
<Route path={/REGEXP[if path !== "/" && path does NOT include the word "article"]/} component={ErrorDefault} />
<Route path={["/article/:id", "/"]}>
<Home />
</Route>
</Switch>
在底部你会看到我不得不将 404 组件放在我的 index 路由上方,因为如果我使用 catch all 路由,404 永远不会被命中,它只是导航到 index 路由但维护不正确的 URL . 例如,输入 http://localhost:3000/mistake 会将我带到索引路由。我不希望这样,因为我依靠 url 来呈现模块化组件,如果路径不正确,它就不起作用。
所以我需要强制任何未声明的路径指向一个 404 页面,我可以在其中显示一条消息和一个返回主页的链接。
【问题讨论】:
-
考虑到您可以处理每个
line,为什么不检查line != '/'和!line.find("article")(但是您在javascript 中实现这些检查)? -
@rturrado 谢谢,老实说,我有点菜鸟,我不确定我可以在我的反应应用程序中实现它。如果您不介意看一下,我已经用我的代码和对问题的简要进一步解释编辑了我的原始帖子?
-
对不起,我帮不上忙!我从严格的正则表达式的角度来处理这个问题,但我对 javascript 或反应一无所知。对不起!
-
完全不用担心!
标签: javascript reactjs regex http-status-code-404