node.js - Express redirect based off URL -
i'm using express
& node.js
.
router.get('/:year?/:month?/:day?', function(req, res) { var date = moment(); if (req.params.year && req.params.month && req.params.day) { var datestring = req.params.year + " " + req.params.month + " " + req.params.day; var tempdate = moment(datestring, "dd mm yyyy"); if (tempdate.isvalid()) { date = tempdate; } } .catch(function (err) { console.error(err); res.send("error"); }); });
the above isn't full code route. need pointers. i'm using moment.js(http://momentjs.com/) grab current date, format , pass through url in route.get
request.
however, don't want user able go past date. if date has been , user tries navigate want redirect them current date.
.then (function(){ var pastdate = function(req, res) { if (req.query.[pastdate]) { res.redirect('/'); } else {} } })
i don't think the syntax correct. not sure if i'm looking on right lines in how i'd this.
thanks help.
i looked through code , looks inconsisten , don't understand you're trying do, can narrow down this:
router.get('/:year?/:month?/:day?', function (req, res) { var year = req.params.year; var month = req.params.month; var day = req.params.day; if (year && month && day) { var requestdate = moment(day + ' ' + month + ' ' + year); var today = moment(); if (requestdate.isvalid() && !requestdate.isbefore(today)) { // set , valid, stuff request } else { // invalid date or requested date before today // redirecting /year/month/day of day, e.g /2015/04/31 return res.redirect('/' + today.year() + '/' + today.month() + '/' + today.date()); } } });
moment has isbefore
method handy these kind of tasks.
you should use bit more variables in code it's easier work with! :)
Comments
Post a Comment