Reputation: 93
I have been struggling to implement a 404 page in deno(oak server framework) - if i load any addtress that does not exist, i get just a blank page..
tried: (page404MiddleWare.ts):
import {Context, exists, send} from "./deps.ts";
export const page404MiddleWare = async (ctx: Context, next: Function) => {
ctx.response.body = "404 page";
await next();
}
But that seems like a bad practise.
Upvotes: 5
Views: 1639
Reputation: 1330
I've created this middleware. Use it as most first, may be after logger middleware.
export const errorBody =
(): Middleware =>
async ({ request, response }, next) => {
await next();
const status = response.status;
if (
status >= 400 &&
request.method === "GET" &&
response.writable &&
!response.body
) {
response.type = "text/plain; charset=UTF-8";
response.body = `HTTP ${status}`;
response.status = status;
}
};
const app = new Application();
app.use(loggerMiddleware.logger);
app.use(errorBody());
app.use(loggerMiddleware.responseTime);
app.use(router.routes());
app.use(router.allowedMethods());
Upvotes: 0
Reputation: 33
The question's old, but this worked for me:
const app = new Application();
// add your middlewares here
app.use(router.routes());
app.use(router.allowedMethods());
// and then redirect to 404, if there wasn't found any route earlier
app.use((context: Context) => {
context.response.type = "text/html; charset=utf-8";
context.response.status = 404;
context.response.body = "<h1>404, Page not found!</h1>";
});
Essentially you add a custom middleware, which returns 404 after it goes through your earlier middlewares, without returning any response. Hope it helps someone! :)
Upvotes: 0
Reputation: 11717
I would add a default route for all non existing urls and redirect user there:
router.get("/(.*)", async (context: Context) => {
context.response.status = 404;
context.response.body = "404 | Page not Found";
});
and all rest routes:
...
...
router.get(
"/api/users",
UserController.fetch,
);
router.get(
"/api/me",
UserController.me,
);
...
...
Checkout my Deno REST boilerplate project for more details: https://github.com/vicky-gonsalves/deno_rest
Upvotes: 8