Negative lookahead regex
Maybe this will come handy at times:
const app = require('express')()
app.get(/^\/(?!login\/?$)/, (req, res) => { res.send('general') })
app.get('*', (req, res) => { res.send('special') })
app.listen(3000)
With this, you would get:
/ general
/asdf general
/login special
/login/ special
/login/asdf general
/loginasdf general
Or if you also want /login/asdf
to be special
:
app.get(/^\/(?!login($|\/.*))/, (req, res) => { res.send('general') })
In particular, when I Googled here I was thinking about the case of serving static frontend files on the same server that does the API for a SPA:
const apiPath = '/api';
const buildDir = path.join(__dirname, 'frontend', 'build');
// Serve static files like /index.html, /main.css and /main.js
app.use(express.static(buildDir));
// For every other path not under /api/*, serve /index.html
app.get(new RegExp('^(?!' + config.apiPath + '(/|$))'), function (req, res) {
res.sendFile(path.join(buildDir, 'index.html'));
});
// Setup some actions that don't need to be done for the static files like auth.
// The negative lookahead above allows those to be skipped.
// ...
// And now attach all the /api/* paths which were skipped above.
app.get(apiPath, function (req, res) { res.send('base'); });
app.get(apiPath, function (req, res) { res.send('users'); });
// And now a 404 catch all.
app.use(function (req, res, next) {
res.status(404).send('error: 404 Not Found ' + req.path)
})
// And now for any exception.
app.use(function(err, req, res, next) {
console.error(err.stack)
res.status(500).send('error: 500 Internal Server Error')
});
app.listen(3000)
Tested on express@4.17.1, Node.js v14.17.0.