How to deal when calling a wrong endpoint using app.get?
Asked Answered
T

3

5

I have several endpoints defined. I am doing the automation of all of them and in addition defining some scenarios where I should get an error.

For instance, one of the endpoints is: '/v1/templates'.

Now, imagine that by error, the user types '/v1/templatess'.

I am using app.get to deal with the known endpoints like this:

app.get(
    '/v1/contents/:template_component_content_id',
    controllers.template_component_contents.getById.bind(controllers.template_component_contents)
);

Is there any way to say that in case that the endpoint called does not match with any of the app.get() options, throw an ERROR?

Thanks in advance.

Tiddly answered 28/9, 2018 at 9:20 Comment(0)
G
4

In app.js write this below where you've imported routes

const express = require('express');
const app = express();

app.use((req, res, next)=>{
  res.status(404).send({message:"Not Found"});
});

if you want to display some page from backend

app.use((req, res, next)=>{
  res.render('./path/to/file');
});

For more reference check this github project

nodejs_boiler_plate/app.js

Gat answered 9/10, 2018 at 8:13 Comment(0)
D
4

You can handle 404 withing express handlers.

In your main express file(may be index.js or app.js) just put following after your routing middleware.

app.use("/v1", your_router);

// catch 404 and forward to error handler
app.use((request, response, next) => {
  // Access response variable and handle it
  // response.status(404).send("Your page is not found"))
  // or
  // res.render("home")
});

You can achieve this with additional route also with

app.get('*', (req, res) => {})

But it's not advisable as it's regex operation and express already providing the inbuilt handler to handle 404 routes.

Doucet answered 11/10, 2018 at 8:53 Comment(0)
S
1

Try Something Like:

app.get('*', (req, res) => {
  res.send({error: "No routes matched"});
  res.end();
})

Add this code as a last route in your routes and i hope so will do the magic.

Selina answered 28/9, 2018 at 10:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.