How to show custom message of route not found in expressjs? - node.js

I used this code at the bottom of app.js
app.use(function (req, res) {
res.send('Route Not Found');
})
But it executes in every request. I want to execute it only when route is not found.

This works fine. Make sure to place app.get('*' ... at the end of each file with routes if you are including external routes files.
const express = require('express')
const app = express()
app.get('/', function(req, res){
res.status(200).send('GET /')
})
app.get('/a', function(req, res){
res.status(200).send('GET /a')
})
app.get('*', function(req, res){
res.status(404).send('404')
})
app.listen(3000)

Put your routes handler before :
app.get("/a", require("./controllers/handler1.js"); // catch get route on a
app.get("/b", require("./controllers/handler2.js"); // catch get route on b
app.post("/a", require("./controllers/handler1.js"); // catch post route on a
// error handler, if no route has been caught
app.get("/*", function(req, res){ res.send("404 not found"); res.end();});
app.post("/*", function(req, res){ res.send("404 not found"); res.end();});

Related

NodeJS Express middleware goes to next one without next()

I am trying to learn Express for NodeJS but I came across this:
I am trying to add 2 middlewares depeding on url, so on the /user to do something and on root to do something different. However the root middleware is always called even if i dont use next() and if i access the "/" url, the root middleware is called twice.
const express = require('express');
const app = express();
app.use('/user', (req, res, next) => {
console.log('In user middleware ');
res.send('<h1>Hello from User page</h1>');
});
app.use('/', (req, res, next) => {
console.log('In slash middleware !');
res.send('<h1>Hello from Express !</h1>');
});
app.disable('etag');
app.listen(3000);
it should be get or post not use
-get or post are routes
-use is middleware function
check this
const express = require('express');
const app = express();
app.get('/user', (req, res, next) => {
console.log('In user middleware ');
res.send('<h1>Hello from User page</h1>');
});
app.get('/', (req, res, next) => {
console.log('In slash middleware !');
res.send('<h1>Hello from Express !</h1>');
});
app.disable('etag');
app.listen(3000);
From an issue at GitHub.com
https://github.com/expressjs/express/issues/3260
Hi #davidgatti my "root path middlware" I assume you are talking about
nr_one. If so, yes, of course it is executed on every request; app.use
is a prefix-match system. Every URL starts with /, so anything mounted
at / will of course get executed :)
Okay, I can't confirm this but I suspect from the tutorial you are following you might be missing a line.
As you said, app.use is a middleware which will be added to all the route
So when you load say some url where you expect the middleware then it won't know about the request type (post, put, delete or get request).
Any alternate for this could be to try something like this
app.use('/user', (req, res, next) => {
if (req.method === 'GET') {
console.log('In user middleware ');
res.send('<h1>Hello from User page</h1>');
}
});
Again, Just check and compare his code thoroughly
Adding this link from Justin's answer for reference
In order to avoid such a problem, you have to use the return keyword.
When you send a file to the server, use return.
Try the following code,
const express = require('express');
const app = express();
app.use('/user', (req, res, next) => {
console.log('In user middleware ');
return res.send('<h1>Hello from User page</h1>');
});
app.use('/', (req, res, next) => {
console.log('In slash middleware !');
return res.send('<h1>Hello from Express !</h1>');
});
app.disable('etag');
app.listen(3000);
At line 13 and 8, I used the return keyword.
So when you make http://localhost:3000/ request, you will receive
Hello from Express !
And whenever you make http://localhost:3000/user request, you will receive
Hello from User page

Express route not working - nodejs

I have a simple scenario. I am following Max tutorial.
My http://localhost:3000/message always returns index page. That is only the first route is working. The new route is not working. I am simply trying to put node.hbs on /message
/routes/app.js
var express = require('express');
var router = express.Router();
router.get('/', function (req, res, next) {
res.render('index');
});
router.get('/messsage', function (req, res, next) {
res.render('node', { message: 'hello' });
});
module.exports = router;
app.js
var appRoutes = require('./routes/app');
app.use('/', appRoutes);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
return res.render('index');
});
Your code is working. The requested URL http://localhost:3000/message is not matching any of your declared paths so it is defaulting to your custom 404 page which is the same as your index page. Without changing your code and simply requesting http://localhost:3000/messsage will match the path of /messsage on your router. It's a typo. 😉

Express JS Doesen't Work

I have a weird problem about Express.js
I have code like this
app.get('/', function(req, res) {
res.send('Homepage');
});
app.get('/developers', function(req, res) {
res.send('Developers');
});
When i go to my localhost, i see Homepage text, when i go to /developers page, i see developers text, but when i go to /developers/developer page, i can't see the result.
app.get('/developers/developer', function(req, res) {
res.send('Developer test');
});
Why first and second routes work and why third route doesen't work?
This is because of the order of the route you have entered. app.get matches /developers first and follows the callback for it only. Try passing /developers/developer route above the /developers route. It will work.
Like this
app.get('/', function(req, res) {
res.send('Homepage');
});
app.get('/developers/developer', function(req, res) {
res.send('Developer test');
});
app.get('/developers', function(req, res) {
res.send('Developers');
});
Also, you can inline the /developers/developer within the /developers route
index.js
var developer = require('developer');
app.get('/', function(req, res) {
res.send('Homepage');
});
app.use('/developers', developer());
developer.js
var router = express.Router();
var developer = function() {
var api = router();
api.get('/', function(req, res) {
res.send('Developers');
});
api.get('/developer', function(req, res) {
res.send('Developer test');
});
};
module.exports = developer;

How do I POST/GET to the root of a route?

In my very simple app I have a users route which is hit when I browse to http://localhost/api/users
Is it possible for me to handle a post or get request to that url without appending anything extra to the route? Using the code below the route handler fires when I post to http://localhost/api/users/new but not to http://localhost/api/users and when I try get http://localhost/api/users/13 but not http://localhost/api/users
I know I could use router.post('/', function(req, res) {}); to post to http://localhost/api/users/ but that extra slash seems inelegant
app.js
var express = require('express');
var users = require('./routes/user');
var app = express();
app.use('/api/users', users);
module.exports = app;
routes\user.js
var express = require('express');
var User = require('../models/user');
var router = express.Router();
router.post(function(req, res) {
// post to root
});
router.post('/new', function(req, res) {
// post to /new
});
router.get(function (req, res, next) {
// get root
});
router.get('/:id', function (req, res, next) {
// get /id
});
module.exports = router;
in routes/user.js, you can simply write:
router.post('/', function (req, res, next) {
// post to /api/user or /api/user/
});
router.get('/', function (req, res, next) {
// get /api/user or /api/user/
});
This would work for both: http://localhost/api/users as well as http://localhost/api/users/
Also, there's nothing inelegant about having a / at the end of the url!
You can use an empty route like this :
router.get("", function (req, res, next) {
// get root
});
You will be able to access to /api/user as well as /api/user/
Also you can handle the route with the route method of router to simplify the code and make it more "elegant" :
router.route('/')
.get(function(req, res){}) // GET method of /api/users
.post(function(req, res){}) // POST method of /api/users
.put(function(req, res){}) // PUT method of /api/users
.delete(function(req, res){}) // DELETE method of /api/users
http://expressjs.com/es/api.html#router.route

Express router - Why is this route with parameters not working as expected?

I'm confused by this. Why can I see this at the url http://localhost:1337/admin/hello/holly but not at the url http://localhost:1337/admin/users/holly? It's sending text right? the res.send (sending 'hello' to the page). But surely the adminRouter.get should be pulling the 2nd url (with the word 'users' in the path) ? It's basically doing the opposite of what I 'm expecting it to do.
Here's the code snippet.
// route with parameters (http://localhost:1337/admin/users/:name)
adminRouter.get('/users/:name', function(req, res) {
res.send('hello ' + req.params.name + '!');
});
** edit: Here's the whole code with the other routes:
// load the express package and create our app
var express = require('express');
var app = express();
// send our index.html file to the user for the home page
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
// get an instance of the router
var adminRouter = express.Router();
// route middleware that will happen on every request
adminRouter.use(function(req, res, next) {
// log each request to the console
console.log(req.method, req.url);
// continue doing what we were doing and go to the route
next();
});
// route middleware to validate :name
adminRouter.param('name', function(req, res, next, name) {
// do validation on name here
// blah blah validation
// log something so we know its working
console.log('doing name validations on ' + name);
// once validation is done save the new item in the req
req.name = name;
// go to the next thing
next();
});
// route with parameters (http://localhost:1337/admin/users/:name)
adminRouter.get('/users/:name', function(req, res) {
res.send('hello ' + req.params.name + '!');
});
// create routes for the admin section
// admin main page. the dashboard
adminRouter.get('/', function(req, res) {
res.send('I am the dashboard!');
});
// users page
adminRouter.get('/users', function(req, res) {
res.send('I show all the users!');
});
// posts page
adminRouter.get('/posts', function(req, res) {
res.send('I show all the posts!');
});
// apply the routes to our application
app.use('/admin', adminRouter);
// start the server
app.listen(1337);
console.log('1337 is the magic port!');
So the answer to this one was to just manually restart my server and the problem corrected itself.
Why it had gotten itself in a twist and was doing the reverse of what it should have been doing who knows, but on restarting the server it worked correctly.

Resources