app.use() does not log any incoming requests - node.js

I have a few api calls set up via express and router. I am trying to debug and understand the working of the router. I have a logger set up, and trying to log all the api calls. However, the calls are never logged. All the api endpoints get called and the application works as expected though. Below is an example of what I am trying to do. Can someone please let me know what could be missing here?
const logger = require('./config');
const app = express();
// routes needed for the app
app.use(require('./routes/apis'));
app.use('/api', (req, res, next) => {
logger.info('in /api call');
});

you need to change the order of the middleware:
const logger = require('./config');
const app = express();
app.use('/api', (req, res, next) => {
logger.info('in /api call');
});
// routes needed for the app
app.use(require('./routes/apis'));

Related

How to retrieve route info from request object in nodejs/express

I would like to check the route when receiving a request in nodejs (10.16) and express (4.16) project. The server listens to port 3000 on localhost. Here is a users route:
const users = require('../routes/users');
module.exports = function(app, io) {
app.use('/api/users', users);
}
In route users.js, there is:
router.post('/new', async (req, res) => {...}
When a route is called (ex, ${GLOBAL.BASE_URL}/api/users/new), how do I know which route is being called from the param req?
OK, what I understand, you are having troubles accessing your user routes (declared in your users.js file) from your application root file.
Because you are modularize your routes, you need to make sure you export your routes module to gain access from another file:
app.js:
const UserRouter = require('../routes/users');
module.exports = function(app, io) {
app.use('/api/users', UserRouter);
}
users.js:
const UserRouter = express.Router()
UserRouter.post('/new', async (req, res) => {...};
module.exports = UserRouter;
If you need the path of request, Try this:
var path = url.parse(req.url).pathname;
console.log('path:', path);

Why does Express Middleware not fire when preceded by app.use(express.static(path.join(...)));

I am trying to de-bug an issue in my very simple express backend boilerplate. I have a universal middleware that I want to fire with every single request that hits the server (Essentially, I'm just trying to set a cookie.)
const express = require('express');
const path = require('path');
const uuidv4 = require('uuid/v4');
const cookieParser = require('cookie-parser')
const app = express();
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'client/build')));
app.use('/', (req, res, next) => {
console.log(req.cookies)
if (!req.cookies['audience_tracking_id']) {
console.log('Processed Request - User Does Not Have Cookie.')
const uniqueID = uuidv4();
res.setHeader('Set-Cookie', [`audience_tracking_id=${uniqueID}`, `contentFocus=${randomProductName()}`]);
}
next();
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/client/build/index.html'))
});
app.use(function(err, req, res, next) {
console.log(err)
res.status(err.status || 500).send();
});
const port = process.env.PORT || 6000;
app.listen(port);
console.log(`Audience Service Host listening on ${port}`);
The application includes a React Front-End which is hosted on Heroku, and I am serving the static build files through Express within the same container.
The issue is - Whether I use Postman to locally send a GET request to this file in localhost:6000, OR whether I access the container on Heroku, the console.log() fails to fire - and maybe the rest of the middleware.
However, if I move this line below the cookie middleware:
app.use(express.static(path.join(__dirname, 'client/build')));
OR, If I just comment it out, my middleware fires and the console.log() shows up. It was a simple fix, but I have no idea why this actually happens, does anyone know what I am doing wrong with this code that makes the middleware fail as-is?
It is because your "static file" middleware will try to match all request to your server:
app.use(express.static(path.join(__dirname, 'client/build')))
Your request "GET localhost:6000/*" will be routing to "static file" middleware before "cookie" middleware. If the "static file" middleware find the file exist, the response will be end with the file. If not, the middleware's action is relate to the option(fallthrough), you can get more detail on server-static's option
I suggest to set root mount path for static file middlware:
app.use("/dist", express.static(path.join(__dirname, 'client/build')))
If you want to check cookie in all request, use this format:
app.use((req, res, next) => {
// Do something
})

Is the express app object also an express middleware?

I just started learning express and I read that an express middleware is a Javascript function to handle HTTP requests. It accepts 3 parameters:- req, res and next.
When I tried the following code block:-
const express = require('express');
const app = express();
var x = app.get('/', function(req, res){
res.send('Hello World!');
} );
console.log(x.toString());
app.listen(3000, function() {
console.log('Example app listening on port 3000!');
} );
I see the following output:-
function(req, res, next){
app.handle(req, res, next);
}
So is the express app object also an express middleware?
I'm sorry if this is a silly question, but wanted to have an insight nevertheless.
The .get() function is yes. the majority of the express functions .use() etc are really just middlewares for specific tasks. .get checks the req object against the url provided, if it's a match then it runs it's code. If it isn't then it continues to next() through all the other .get() middlewares.
The entire ecosystem of express is middlewares going to more middlewares

json-server middleware not working as expected

using node.js/Express/json-server
I am trying to check ( and modify) the request url sent to my API json-server. I wrote as stated the following middleware in my app server.js
// API JSON-SERVER
const jsonServer = require('json-server')
const apiServer = jsonServer.create()
const apiMiddlewares = jsonServer.defaults()
apiServer.use(apiMiddlewares)
...
apiServer.use((req, res, next) => {
console.log('REQUEST: ', req)
next() // Continue to JSON Server Router
})
...
apiRouter = jsonServer.router(path.join(__dirname, '..', 'server', 'db-dev.json'))
app.use('/api', apiRouter)
but I never get the request displayed
where am I wrong ?
I looked here
https://github.com/typicode/json-server/issues/253
and it seems to me that you never want to instantiate the jsonServer, but only use the router. Since you are using the express server, you should attach the middleware to that.
const express = require('express')
const jsonServer = require('json-server')
const app = express()
app.use((req, res, next) => {
console.log('REQUEST: ', req)
next() // Continue to JSON Server Router
})
app.use('/api', jsonServer.router(path.join(__dirname, '..', 'server', 'db-dev.json')))

middlewares not running in Express

Based on Express docs, a middleware must run each time app is launched following this code:
var app = express();
app.use(function (req, res, next) {
console.log('Time:', Date.now());
next();
});
Well, trying to execute with the most simple possilbe example middleware never is excuted:
var express = require('express');
var middleware = require('./middleware');
var app = express();
app.use(function (req, res, next){
console.log('MIDDLEWARE');
next();
});
module.exports = app;
Middleware never runs.
Also tryed to make it working from a separated file, but never runs.
Thanks
Middleware are lunch when there are any request to the server.
Create a route and send a request to that, the middleware would be lunched.
Ups, seems to be they're launched when recieves a request. So using Postman it worked.

Resources