How to set verification of session for all routes?
if(req.session.lang) req.session.lang
else req.session.lang = "pt";
const tradutor = require('../scripts/lang/lang-'+req.session.lang+'');
var traduPT = new tradutor();
this is my code. i want use for check in all routes, maybe something like adding the code and just applying the request on the routes, but how and where to do this code outside the routes?
You can create route-specific middleware.
// validate.js
export const validateSession = (req, res, next) => {
// if the user is logged in, continue
if (req.session.isLoggedIn) return next();
// otherwise, don't continue and go back to the /home route
res.redirect('/home');
};
Then pass it in as the second argument when defining your route:
// main.js
import { validateSession } from './validate.js';
app.get('/dashboard', validateSession, (req, res) => { /* ... */ });
app.get('/login', validateSession, (req, res) => { /* ... */ });
app.get('/foo', validateSession, (req, res) => { /* ... */ });
Related
I have the problem on routers. My main route /weather working, but others routers on him don't.
app.js
const express = require('express');
const weatherRoute = require('./back/routes/weatherRouter.js');
const app = express();
app.use(bodyParser.json());
app.disable('etag');
app.use('/weather', weatherRoute);
weatherRouter.js
const router = express.Router();
router.get('/', async (req, res) => {
try {
const wholeData = await WeatherInfo.find();
res.json(wholeData);
} catch (err) {
res.json({ message: err })
}
});
router.get('/now', (req, res) => {
res.send("ITS NOT WORKING");
});
module.exports = router;
the problem is that localhost:5000/weather working perfect, but when I want to use some other routers on that Route e.g. localhost:5000/weather/now that's not working
Any ideas what I'm doing wrong ?
UPDATED :
it works, when between those routers is no others routers.
e.g.
router.get('/', async (req, res) => {
//working
}
router.post('/:add', async (req, res) => {
//working
}
router.get('/now', async (req, res) => {
//doesnt work
}
If I move /now above /add router it works perfect. Can someone explain why is this happening ?
Define actual path in path section likerouter.post('/weather/now', (re, res) => {
//Handel re
}
I found the solution.
The routers position is matter. Reference to explanation
My last router didn't work, because another router already catched him.
app.get('/:add', function (req, res) {
// this will match all /a, /b .. including /new
res.end('done!');
});
app.get('/now', function (req, res) {
// this is never called
res.end('done!!');
});
Hi I am facing the problem that I need to log each incomming request and the associated responses in my database. My current solution looks like the following:
./routes/customer.js
router.get('/', async (req, res, next) => {
req.allCustomers = await fetchAllCustomers();
res.status(200).send(req.allCustomers);
next(); // <- this is my personal problem
});
./middleware/logging.js
module.exports = function (req, res, next) {
db.query(
`INSERT INTO logging SET ?`,
{
request: JSON.stringify([req.body, req.params]),
response: JSON.stringify(req.response)
}
);
}
routes declaration
module.exports = function(app) {
app.use(express.json());
app.use('/api/customers', customers); // <- ROUTE ./routes/customer.js
app.use(logging); // <- MIDDLEWARE ./middleware/logging.js
}
I already mentioned my problem in my first piece of code. It is really repetitive to call next() in every route manually and I would like to avoid this. I already tried to load the middleware before all routes, call next() in the middleware function and execute my db query afterwards but I do not have the response at this point because of the async functionality.
Is there any way to handle this situation or will I need keep calling next() at the end of each route function?
If you don't want to call next() from your routes, you cannot have middleware run after them. It needs to be placed before. But can you get the response inside a middleware that runs before the route? The answer is yes!
It may be a little hacky, but since your route uses res.send(), you can use that to your advantage. By running before your route, your middleware can hijack that res.send function, to make it do other stuff.
./routes/customer.js
router.get('/', async (req, res, next) => {
req.allCustomers = await fetchAllCustomers();
res.send(req.allCustomers); // We'll hijack this
});
./middleware/logging.js
module.exports = function (shouldBeLoggedFunc) {
return function (req, res, next) {
if (shouldBeLoggedFunc(req)) {
// Store the original send method
const _send = res.send;
// Override it
res.send = function (body) {
// Reset it
res.send = _send;
// Actually send the response
res.send(body);
// Log it (console.log for the demo)
console.log(`INSERT INTO logging SET ?`, {
request: JSON.stringify([req.body, req.params]),
response: JSON.stringify(body)
});
};
}
next();
};
};
routes declaration
function shouldBeLogged(req) {
// Here, check the route and method and decide whether you want to log it
console.log(req.method, req.path); // e.g. GET /api/customers
return true;
}
module.exports = function(app) {
app.use(express.json());
app.use(logging(shouldBeLogged)); // <- Place this before your routes
app.use('/api/customers', customers);
};
when you use express.Router class like you already did and then use this code
app.use('/api/customers', customers);
you don't have to write 'next()' inside callback function in router.get .
there is an example
create a router file named birds.js in the app directory, with the following content:
var express = require('express')
var router = express.Router()
// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
console.log('Time: ', Date.now())
next()
})
// define the home page route
router.get('/', function (req, res) {
res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
res.send('About birds')
})
module.exports = router
Then, load the router module in the app:
var birds = require('./birds')
// ...
app.use('/birds', birds)
How to export a variable in node js that initialize after click on button?
File from which i export:
router.post('/', (req, res) => {
let settings = req.body;
module.exports.settings = settings;
res.send('/testroom');
});
File from which i import
let { settings } = require('./pretest');
router.get('/', async (req, res) => {
console.log('settings', settings);
res.sendFile(path.join(__dirname, '../public/html/testroom.html'));
});
you are almost got it right, but when you get the value on the other route it will be already declared and initialized with the first value of the setting
router.post('/', (req, res) => {
let settings = req.body;
exports.settings = settings;
res.send('/testroom');
});
router.get('/', async (req, res) => {
// here its scoped with route when its called its gets the current value
let { settings } = require('./pretest');
console.log('settings', settings);
res.sendFile(path.join(__dirname, '../public/html/testroom.html'));
});
I have the following .post() request:
const express = require('express');
const router = express.Router();
const search_controller = require('../controllers/searchController');
const result_controller = require('../controllers/resultController');
//Search Routes
router.post('/', search_controller.search_create_post);
module.exports = router;
Could I add a second callback to it so that the first callback is run, then the second callback as such:
router.post('/', search_controller.search_create_post, result_controller.result_create_post)
Would I need a next() somewhere in those create functions? And could I also pass data from the search_create_post callback to the result_create_post callback? I would want to pass in the newly created Search object's id.
My current search_controller.search_create_post function is a such:
exports.search_create_post = (req, res, next) => {
let newSearch = new Search({ search_text: req.body.search_text });
newSearch.save((err, savedSearch) => {
if (err) {
console.log(err);
} else {
res.send(savedSearch);
}
})
};
You might be able to use like this (based on how your functions are written):
// option A
router.post('/', search_controller.search_create_post, result_controller.result_create_post)
// options B
router.post('/', search_controller.search_create_post)
router.post('/', result_controller.result_create_post)
If search needs to pass data to result, you could set req.search_data in search_create_post and then get the value in result_create_post.
Take a look at https://expressjs.com/en/guide/using-middleware.html. There are a few good examples on this page.
app.get('/user/:id', function (req, res, next) {
console.log('ID:', req.params.id)
next()
}, function (req, res, next) {
res.send('User Info')
})
// handler for the /user/:id path, which prints the user ID
app.get('/user/:id', function (req, res, next) {
res.end(req.params.id)
})
based on your comment below:
You might be able to do this...
exports.search_create_post = (req, res, next) => {
let newSearch = new Search({ search_text: req.body.search_text });
newSearch.save((err, savedSearch) => {
if (err) {
console.log(err);
} else {
req.searchData = savedSearch;
}
next();
})
};
i come to you because i'm stuck for rewrite my url in javascript.
For example when user make a request for deposit page , my url looks like '/member/deposit' but i just want '/deposit'. i'm using a MVC architecture.
index.js // Where i define all routes file
const
homeRoute = require('./home'),
memberRoute = require('./member');
function init(server) {
server.get('*', function (req, res, next) {
res.locals.user = req.user || null;
return next();
});
server.use('/', homeRoute);
server.use('/member', memberRoute);
}
module.exports = {
init: init
};
router member.js // Where i define all member routes
const
express = require('express'),
memberController = require('../controllers/member');
let router = express.Router();
router.get('/*', function(req, res, next){
if (req.session.user && (req.session.user.role == "member"))
next();
else
res.redirect('/login');
});
router.get('/', memberController.deposit);
router.get('/deposit', memberController.deposit);
router.get('/withdraw', memberController.withdraw);
module.exports = router;
controller member.js // where all code is executed before rendering
function deposit(req,res){
res.render('member/deposit',{
title:'Deposit'
});
}
function withdraw(req,res){
res.render('member/withdraw',{
title:'Withdraw'
});
}
Any help would be appreciated, i've not find response on stackoverflow
It can be use this way:
server.use('/', homeRoute);
server.use('/', memberRoute);
As long as the link in homeRoute and memberRoute have no duplication.
Or
The complete rewrite of url can be done as in the following link:
https://gist.github.com/ramonfritsch/06893c1c561d670687a9aee3bbc4e9c7