How can I conditionally suppress logging in Express (or Connect)? - javascript

When using the logger middleware which is part of Connect (as well as Express), I would like to be able to disable logging on certain requests, say by setting a flag on the response or something.
I managed to do it by saying:
res.doNotLog = true;
and then, deep in logger.js (part of the Connect module), I put
if(res.doNotLog) return;
in the right place. But of course I don't want to be modifying code in the module itself. Is there any way I can cause the same to happen without having to hack the module?
Edit:
This worked:
var app = _express.createServer();
// set 'hello' routing...note that this is before middleware
// so it won't be logged
app.get('/sayhello', function(req, res) {res.send("hey");});
// configure middleware: logging, static file serving
app.configure(function() {
app.use(_express.logger());
app.use(_express.static(__dirname + '/www'));
});
// set 'goodbye' routing...note that this is after middleware
// so it will be logged
app.get('/saygoodbye', function(req, res) {res.send("later...");});

The most obvious thing would be to put the handlers for those requests before the logger. This is easy in pure Connect, not sure how to do it in Express because a lot of the router code is shared between routes. If there were only a few such requests, you could handle them Connect-style earlier in the stack than app.router.

Related

How to handle Error: socket hang up while waiting Node and React

I've been working on a NodeJS express route the accepts a get request, counts and analyzes about 15000+ data, so from my react app (Axios) when I hit the get URL, the processing and analyzing takes more than 4 to 5 min and the socket hangs up on about 2min what should I do to make my react app wait longer or get a response in any other way. Maybe an HTTP 202 has its way but I don't know how to do it, Any Help?
the wise choice is to use websocket or socket-io for such use cases.
but you can also :
use express timeout . to keep the connection alive between the client and the server:
first, install :
npm install connect-timeout
after that change your server entry point(app.js) file.
var express = require('express')
var timeout = require('connect-timeout')
// example of using this top-level; note the use of haltOnTimedout
// after every middleware; it will stop the request flow on a timeout
var app = express()
app.use(timeout('400s'))
app.use(haltOnTimedout)
// Add your routes here, etc.
function haltOnTimedout (req, res, next) {
if (!req.timedout) next()
}
app.listen(3000)
for more details : express official
or if you don't want to install any third-party module :
app.use(function(req, res, next){
res.setTimeout(120000, function(){
console.log('Request has timed out.');
res.send(408);
});
next();
});

Why is Express redirecting infinitely redirecting me?

I am trying to setup a multi language website with Express and NodeJs. My problem is I get redirected what it feels like 100 times and my browser is giving me a error that the webpage is not working because it redirected me too many times.
app.js
app.use('/', (req,res,next) => {
res.redirect('/en-US');
next();
});
app.use('/:lang', indexRouter);
app.use('/:lang/users', usersRouter);
index.js (indexRouter)
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
module.exports = router;
The problem is that this route handler:
app.use('/', (req,res,next) => {
res.redirect('/en-US');
next();
});
will get hit for not only /, but also /en-US. app.use() matches any route handler for which the path is equal to or a subset of the requested path. So, the browser requests "/", you redirect to "/en-US", which then redirects to "/en-US" and so on, an infinite loop.
I don't know the overall URL design of your site to know what the best overall solution is. You can prevent the infinite redirect loop by just changing app.use() to app.get():
app.get('/', (req,res,next) => {
res.redirect('/en-US');
});
But, that will make the redirect only work for GET requests which may or may not be OK. If you want all HTTP verbs to redirect, you could change to app.all():
app.all('/', (req,res,next) => {
res.redirect('/en-US');
});
The important thing to understand here is that app.get(), app.post(), app.all(), etc... all require an exact match for the URL path, whereas app.use() just requires a subset match. This is a little understood aspect of the Express design.
In addition, remove the call to next() after you do res.redirect(). At that point, you've sent the response, you don't want any other request handlers to see the request. You're done with routing.
under your app.js
Try using
app.use('/', router )
How about you try dealing with the '/' route through the app.js directly instead of index.js

Dashing-JS "Hello World" Demo

I am attempting to work with Dashing-JS, a port of a Sinatra based framework project in Ruby, Dashing.IO, to Javascript/Node. Essentially I have the core packages and dependencies for Dashing-JS configured; however, when attempting to run just the sample, I am unable to display anything other than this 404 error rather than a sample dashboard:
NodeJS CLI output is as follows:
The project is not well maintained; however, I am curious if an expert in Node might be able to shed some light on the situation. Is a path reference incorrect?
Notes:
1. server.js is referencing sample.jade.
var dashing = require('new-dashing-js').Dashing();
// Set your auth token here
//dashing.auth_token = 'YOUR_AUTH_TOKEN';
/*
dashing.protected = function(req, res, next) {
// Put any authentication code you want in here.
// This method is run before accessing any resource.
// if (true) next();
}
*/
// Set your default dashboard here
dashing.default_dashboard = 'sample';
dashing.start();
"Sample.jade" is located within the "dashboards" directory

Stuck with server.use()

Im stuck with server.use is node.js. everytime i take server.use(express.static('public')); before server.get , it won't run, then i change server.use(express.static('public')); after server.get() it working well like nothing happened.
can someone tell me what is the difference ?
here my script :
// Depedencies / built-in
import express from 'express';
import { join } from 'path';
import nodeSass from 'node-sass-middleware';
// you can place anything here, except depedencies
import config from './config';
import apiRouter from './api/index';
const server = express();
// Including Middleware
server.use(nodeSass({
src: join(__dirname + 'sass'),
dest: join(__dirname + 'public'),
}));
// everytime i take this before Router, it running, but
// but, the index won't showing up
server.use(express.static('public'));
// Setting up view engine
server.set('view engine', 'ejs');
// Router
server.get('/', (req, res) => {
res.render('index', {
title: 'Hello EJs',
});
});
// if i change after Route, it working well
// server.use(express.static('public'));
server.listen(config.port, () => {
console.log('magic happen on port: ', config.port);
});
I will try to answer, by guesing what's wrong.
1) server.use(express.static('public')); This is just the way to tell your application where to look for static files like JS, CSS, images and other content that page will need to load. More info here . http://expressjs.com/en/api.html#express.static
2) When you use res.render('pathToRenderFile') It will try to find file name with specified engine server.set('view engine', 'ejs'); . If no engine is set you will need to add extension too. By default it will look in views directory. More info here http://expressjs.com/en/guide/using-template-engines.html
So in your case you need to put index.ejs inside views/index.ejs. Then all should work.
3) All of the middleware(middleware functions) like server.use or server.set should be set up before routes.
4) About middleware, and the point of it. Before or after any route you can perform some actions that you may require on request or response objects. For example you need this middleware https://github.com/expressjs/body-parser to have all post data inside req.body object. If you dont include it you will have to parse it yourself. That's why express gives you a good way to handle this cases, using build in or yourown middlewares.
Here is the list of all usefull middlewares https://expressjs.com/en/resources/middleware.html
Middleware functions are executed sequentially, therefore the order of middleware inclusion is important.
There is a good examples here https://expressjs.com/en/4x/api.html#app.use
Hope this helps.

Express routes & Same Object needed in several files

I made an web application where all my server side was in the same file.
To be clear, in my "app.js" i had :
Express routes
Socket.io events and more...
Differents objects reacting with pages events
I want to rework that project to do things properly and i started to do that. I have put my routes in different js files like login.js,subscribe.js, ... in a routes directory.
In my app.js I have added the line : require('./routes')(app);
I have a index.js file in /routes where i had placed my "Express router" which is managing all my routes.
index.js
module.exports = function (app) {
app.get('/signup', require('./subscribe').get);
app.post('/signup', require('./subscribe').post);
app.get('/', require('./login').get);
app.post('/', require('./login').post);
...
}
Is that the correct way to do with routes ?
The problem i meet is that i have an object named usersConnected {} that I fill with some properties when a member is logged in, etc...
This object is in my app.js file and I can't reach it from the other files like login.js...
app.js
// Express routing defined in ./routes/index.js
require('./routes')(app);
// Globals variables
var usersConnected = {};
var rooms = {};
...
login.js
An example of the usage of usersConnected
// If login and password matches with couple in database
usersConnected[login] = {
games: rows[0].games,
kills: rows[0].kills,
deaths: rows[0].deaths,
statut: "ACCUEIL",
adversaire: "NULL",
socket: "NULL",
wsId: "NULL",
room: "NULL",
lsid: funcs.computeRandomLsId(64)
};
And how i export my "route managing"
exports.get = (req, res) => {
if (!req.session.login)
...
}
I have some ideas but I think it's the bad way to proceed like exports my object where I need it or put my object alone in a .js file which will be imported, etc...
If you could give me some trails that would really help me.
Edit : I think my problem is the way i manage my sessions, because usersConnected contains all informations about all users connected... Maybe i should use express-session ?
I recommend you take a look at express-generator: http://expressjs.com/en/starter/generator.html . It provides a quite nice file structure for you to start. Even though it's quite opinionated, I found it very useful when I started and still do.
In the app.js file you will find something like this:
...
var routes = require('./routes/index');
app.use('/', routes);
This is a bit tedius if you have a lot of routes. Here you have a code snippet to do this dinamically. gist
Anyway, the point is that the express generator will help you evacuate your doubts and point you in the right direction.

Categories