如何重定向所有 404 错误
How to redirect all 404 errors
我如何捕获所有 404 错误并重定向到 /app/index。html(我试图满足 Angular 将所有未找到的资源转发到 index.html) ?我认为实现我自己的中间件会奏效,但不确定我是否做对了
public final class ForwardToAngularMiddleware: Middleware {
public func respond(to req: Request, chainingTo next: Responder) throws -> EventLoopFuture<Response> {
do {
let response: Future<Response> = try next.respond(to: req)
return response
} catch let error as AbortError {
if error.status == .notFound && req.http.url.path.starts(with: "/app") {
return Future.map(on: req) { req.redirect(to: "/index.html") }
}
throw error
}
}
}
无论我发送什么 URL,我的程序都不会触发捕获块。我正在这样配置我的中间件:
middlewares.use(FileMiddleware.self)
middlewares.use(ForwardToAngularMiddleware())
middlewares.use(ErrorMiddleware.self)
middlewares.use(SessionsMiddleware.self)
services.register(middlewares)
您可能遇到了几个问题。首先,将来可能会抛出中止错误,在这种情况下,您需要将 catchMap
添加到 next.respond(to:)
调用中以捕捉这种情况。
它也可能不会抛出(尽管这不太可能),因此您可以尝试解包响应并检查状态代码。
你有没有设置断点看看它是否命中它等等?
我如何捕获所有 404 错误并重定向到 /app/index。html(我试图满足 Angular 将所有未找到的资源转发到 index.html) ?我认为实现我自己的中间件会奏效,但不确定我是否做对了
public final class ForwardToAngularMiddleware: Middleware {
public func respond(to req: Request, chainingTo next: Responder) throws -> EventLoopFuture<Response> {
do {
let response: Future<Response> = try next.respond(to: req)
return response
} catch let error as AbortError {
if error.status == .notFound && req.http.url.path.starts(with: "/app") {
return Future.map(on: req) { req.redirect(to: "/index.html") }
}
throw error
}
}
}
无论我发送什么 URL,我的程序都不会触发捕获块。我正在这样配置我的中间件:
middlewares.use(FileMiddleware.self)
middlewares.use(ForwardToAngularMiddleware())
middlewares.use(ErrorMiddleware.self)
middlewares.use(SessionsMiddleware.self)
services.register(middlewares)
您可能遇到了几个问题。首先,将来可能会抛出中止错误,在这种情况下,您需要将 catchMap
添加到 next.respond(to:)
调用中以捕捉这种情况。
它也可能不会抛出(尽管这不太可能),因此您可以尝试解包响应并检查状态代码。
你有没有设置断点看看它是否命中它等等?