express order difference make result different - express

const express = require('express')
const app = express();
app.use('/users', (req, res, next) =>{
res.send('Hello from express Again.')
});
app.use('/', (req, res, next) =>{
res.send('Hello from express.')
});
app.listen(4000, function () {
console.log('console server listening on 4000');
})
when i go to to http://localhost:4000/users it will render: Hello from express Again..
BUT if I change the code order like:
app.use('/', (req, res, next) =>{
res.send('Hello from express.')
});
app.use('/users', (req, res, next) =>{
res.send('Hello from express Again.')
});
Now I do it again: http://localhost:4000/users The result is Hello from express.
I guess it's configuration issue. But I just don't know which configuration.

Yes, the order you declare your routes in Express is important. Routes are matched from first to last in order of declaration and the first route that matches gets the request. If it sends a response and doesn't call next(), then the following routes do not get a chance to run.
Also relevant here is that app.use(somePath, ...) will match any route that starts with somePath. So, this:
app.use('/', (req, res, next) =>{
res.send('Hello from express.')
});
will match every single possible route because they all start with "/".
So, when you do this:
app.use('/', (req, res, next) =>{
res.send('Hello from express.')
});
app.use('/users', (req, res, next) =>{
res.send('Hello from express Again.')
});
And, send a request for /users, then the first route will match everything and thus the second route is never called.
Whereas, when do this:
app.use('/users', (req, res, next) =>{
res.send('Hello from express Again.')
});
app.use('/', (req, res, next) =>{
res.send('Hello from express.')
});
The /users route gets the first chance to match so when you send a request for /users, that /users route gets matched first and takes the request.
Note: You should only be using app.use() when you either want to match all possible http verbs or you WANT the greedy partial match that is in play here. If you don't want one of those, then use the verb-specific version such as app.get(). In your example, if you make both of these app.get(), then it is no longer order-sensitive because app.get() only matches complete path matches and does not do partial matches.
Both of these work the same:
app.get('/', (req, res, next) =>{
res.send('Hello from express.')
});
app.get('/users', (req, res, next) =>{
res.send('Hello from express Again.')
});
and:
app.get('/users', (req, res, next) =>{
res.send('Hello from express Again.')
});
app.get('/', (req, res, next) =>{
res.send('Hello from express.')
});
Because only one of them will match / and only one will match /users.

Related

Why does ExpressJS not match all paths on root app.get('/'

The following express routing matches GET / but not GET /anything/else.
app.get('/', (req, res, next) => {
res.send('I only answer to /');
});
Is Express Routing not prefix-based or "deep"?
I know this works but it seems wrong:
app.get('*', (req, res, next) => {
res.send('I answer to any path');
});
app.get must match the full path and stores it in req.path, whereas app.use matches a prefix and sets req.path to the path after the prefix. You could write
app.use('/', (req, res, next) => {
if (req.method === "GET")
res.send('I answer to all GET requests');
else
next();
});
GET /anything/else would be matched by app.use('/anything', ...), but then req.path = '/else'.
One possible fix although it's not as elegant would be:
app.use(function(req, res, next) => {
res.send('I answer to any path')
});
Make sure to add this to the end of all your Routing. Hope this still helps :)
Have a nice day

How can I route all calls starting with string api to their handlers in an express middleware

I have a express app.js with typical
app.get('/path1', (req, res => {})
app.get('/path2', (req, res => {})
app.get('/path3', (req, res => {})
now I want to catch all routes, starting with api such as below and redirect them to their corresponding handler in express but not sure how to achieve that
/api/path1
/api/path2
/api/path3
I' assuming i can have a catch all api as below
app.all('/api/*', function (request, response, next) { //in a server.js file
//how can i call the corresponding paths here??
// looking for something to do forward to current-route.replace('api','')
// or something like that
})
Maybe a router-level middleware could solve your problem:
const router = express.Router();
router.get('/path1', (req, res => {});
router.get('/path2', (req, res => {});
router.get('/path3', (req, res => {});
app.use('/api', router);
Update:
Use redirect (not that much of a difference to your current solution; not tested):
app.all('/api/*', (request, response) => res.redirect(request.url.replace('/api', '')));
this worked for me, please let me know if there is a better way
app.all('/api/*', function (request, response, next) {
request.url = request.url.replace('/api','');
next();
})

Static files inside `public` folder not being served (NextJS custom server using ExpressJS)

I am working on NextJS app. And I have made a custom server using ExpressJS. The problem is when I run the app using the custom server the app cannot find the static files inside the public folder.
Note: I don't have any problem When I run the app using next dev
My server
const express = require('express');
const next = require('next');
const path = require('path');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const prefix = (path = '') => `/:lang(en|tr)?`.concat(path);
app.prepare().then(() => {
const server = express();
server.get(prefix('/'), (req, res) => app.render(req, res, '/', req.query));
server.get(prefix('/agency'), (req, res) => app.render(req, res, '/agency', req.query));
server.get(prefix('/cases'), (req, res) => app.render(req, res, '/cases', req.query));
server.get(prefix('/blog'), (req, res) => app.render(req, res, '/blog', req.query));
server.get(prefix('/contact'), (req, res) => app.render(req, res, '/contact', req.query));
server.get(prefix('/image.png'), (req, res) => app.render(req, res, '/public/images/avatar01.jpg', req.query));
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
It is because you are not implementing a fallback for when there is no match:
server.all('*', async (req, res) => {
return handle(req, res);
}
will handle all the other routes for you (API routes, public/static folder, etc).

How to isolate or fix no-response (browser hang) after calling passport.authenticate as middleware

I'm trying to use passport.authenticate('local') as middleware with passport-local-mongoose but it doesn't seem to pass control to the subsequent middlewares in my route.
I'm assuming there's an error but the following (err, req, res, next) middleware isn't being called so I'm wondering if I've misunderstood something basic about passport-local in general.
I've spent a few hours trying various things, searching here but I can't find a way to isolate my problem any further or get a better log of where control is going wrong in my route.
I've posted a small reproducible example to GitHub.
This is how I'm setting up BEFORE my routes:
// Get connected
mongoose.connect('mongodb://localhost/pass');
mongoose.Promise = global.Promise;
mongoose.connection.on('error', (err) => { console.error(err.message) });
// Basic user schema using nickname field as username
const Schema = mongoose.Schema;
const userSchema = new Schema({});
userSchema.plugin(passportLocalMongoose, { usernameField: 'nickname' });
const User = mongoose.model('User', userSchema);
// Initialise passport before routes
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser);
passport.deserializeUser(User.deserializeUser);
app.use(passport.initialize());
And this is the route with my passport.authenticate:
app.post('/login',
(req, res, next) => {
console.log('login posted ok');
next();
},
passport.authenticate('local'),
(req, res) => res.send('login successful'),
(err, req, res, next) => {
console.log(err);
res.send('login unsuccessful');
}
);
There are other routes with the pug views and registration.
Registration works fine, in mongo db.users.find() show a good looking entry for the new user.
But my /login post route doesn't get beyond passport.authenticate.
The console.log gets triggered, so I know the route is being called.
Based on my limited knowledge of express and passport, I'm expecting one of those two following middlewares to be triggered, one on success and one if it fails.
Neither is triggering.
Best way to isolate is covered in the authenticate docs under "Custom Callback", I just didn't understand it originally.
NOTE: I've saved the following in the answer branch on my repo, as posted in the question.
app.post('/login',
(req, res, next) => {
console.log('login posted ok');
next();
},
(req, res, next) => {
console.log('authenticating...')
passport.authenticate('local', (err, user, info) => {
console.log(req, res, err, user, info);
next(err);
}) (req, res, next);
},
(req, res) => res.send('login successful'),
(err, req, res, next) => {
console.log(err);
res.send('login unsuccessful');
}
);
What I realised
passport doesn't consider authentication FAIL as an err
it just leaves user null
basically you need to give it success and failure redirects if you want to use middleware form, don't do what I did and try to handle err etc.

How to disable CORS on localhost using expressjs

I want to disable CORS on localhost for a specific url, here is my code
const express = require('express')
const app = express()
const port = 3000
app.use(express.static('files'))
app.all('/no-cors/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "fake");
next();
});
app.get('/', (req, res) => res.send('Hello World!'));
app.get('/sample-json', (req, res) => res.json({"foo": "bar"}));
// it shld show error in console
app.get('/no-cors/sample-json', (req, res) => {
res.json({"cors": "off"});
});
app
.listen(port, () => console.log(Example app listening on port 3000'))
but I open http://localhost:3000/no-cors/sample-json it still show me the json.
Path argument in express().get(path,...) is evaluated as whole string. Path in Express (and URL generally, not only in Express) does not work as folder structure.
That’s why the address /no-cors/sample-json is not catched with your app.all().
If you want it to work, try the path as /no-cors/*