i have one url that is rendering data and url contains some parameter. so when in that same route i can use those parameter but i cant use it in another routes. so can someone help me with how to transfer data from one routes to another.
router.get('/token/:tokenvalue', function(req, res, next){
var token = req.params.tokenvalue;
// globalVariable.token = token;
// console.log(globalVariable.token);
req.token = token;
res.render('candidate.ejs');
})
after showing this page i am using google login so i cant store this token to req variable or somewhere else. so can someone suggest me how to resolve this issue.
There is a NPM package build for that called 'connect-flash'
$ npm install connect-flash
Than in your app.js || server.js ( your main file which boots your server )
var express = require('express');
var flash = require('connect-flash');
var app = express();
app.use(flash());
app.get('/login', function(req, res){
// Set a flash message by passing the key, followed by the value, to req.flash().
req.flash('username', 'Gaurav Gupta')
res.redirect('/profile');
});
app.get('/profile', function(req, res){
// Get an array of flash messages by passing the key to req.flash()
let message = req.flash('username')
res.render('index', { message: message }); // or {message} only es6 feature
});
The flash is a special area of the session used for storing messages. Messages are written to the flash and cleared after being displayed to the user. The flash is typically used in combination with redirects, ensuring that the message is available to the next page that is to be rendered.
Related
There is a passport.js implementation which is being used for LDAP-auth which works. Now the next step is to encrypt the password on the client-side using Crypto-js as follows:
Client-side angular-js controller
$scope.authenticate = function () {
var auth = new login();
auth.username = $scope.username;
auth.password = CryptoJS.AES.encrypt($scope.password); //// HERE
auth.$save(function (response){
console.log(response);
},function(err){
console.log(err);
});
}
Server-side service
.....
.....
app.post('/login', passport.authenticate('ldapauth'), (req, res) => {
console.log("req.user: ",req.user);
req.session.username = req.user[ldap.username];
req.session.userModel = req.user;
res.status(200).send({"success": 'success'});
});
.....
On the server-side service before calling passport.authenticate with the request 'req' the aes encrypted password needs to be decrypted. How can that be implemented here? (The question is not about encryption but how to get data before it gets passed to passport.authenticate as request)
#Abhijay Ghildyal I don't think they understood your question. It is indeed possible to intercept the request before it gets passed to passport.authenticate(). What you'd want to do is to add this passage of code to your express.js or whichever file you did your express server implementation in. Also I am decrypting the request.body here instead of req.user since at that point of time the user is not yet logged in, however if it's different in your case then that's fine you can decrypt req.user the same way. (The variable app here is the name of your server i.e var app = express();)
app.use(function(req, res, next) {
if(req.url === '/login'){
//CryptoJS.AES.decrypt() is Assumed to be the decrypter function here.
req.body = CryptoJS.AES.decrypt(req.body);
console.log(req.body); //To view decrypted body
}
next();
});
That is it. This middleware function will be reached first before the passport.authenticate() function. Just make sure if you're applying this to req.body you add these lines of codes first, after importing the bodyParser (bodyParser = require('body-parser');) before the passage above.
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
I am new to Node and Express.
I've got a static html page where the users posts his username via ajax to my server. Then I want to redirect him to another html file.
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(__dirname + "/public/arena.html"));
app.get('/',function(req,res){
res.sendFile(__dirname + "/public/index.html");
});
app.post('/login',function(req,res){
var username=req.body.username;
console.log("User name = "+username);
res.redirect(__dirname + "/public/arena.html");
});
var server = app.listen(3000);
I get the username and also the respond in the browser but the server does not redirect me to arena.html. I also don't get any errors.
Why are these "easy" things so difficult in Node?
Thank you guys so much for your help.
The problem in this case is that it looks like you had some test (debugging?) code inserted into your POST route that is stopping the redirect call from running.
Here's the modified (corrected) version of your program, which will redirect the user in the way you want:
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(__dirname + "/public/arena.html"));
app.get('/', function(req, res) {
res.sendFile(__dirname + "/public/index.html");
});
app.get('/arena', function(req, res) {
res.sendFile(__dirname + "/public/arena.html");
});
app.post('/login', function(req, res) {
var username = req.body.username;
console.log("User name = " + username);
// Note how I'm redirecting the user to the /arena URL.
// When you issue a redirect, you MUST redirect the user
// to a webpage on your site. You can't redirect them to
// a file you have on your disk.
res.redirect("/arena");
});
app.listen(3000);
I had to do a couple of things to get this working:
Get rid of your call to res.end. Whenever you call res.end, it will END the request, so any code that happens AFTER that call in the route will not run.
I had to create a new route for /arena. This just renders the arena.html file that you've created. This is required if you want to 'redirect' the user to an arena page.
I had to update your redirect code to actually redirect the user to /arena (the new route I created in step 2), so that the user will then hit your /arena route, and finally get back the template you are trying to show them.
Your res.redirect function is never executed because you are returning from function right before that statement.
You pass a URL to res.redirect(). That URL should be a URL that you have an appropriate route for that will serve the desired file.
Instead you are doing:
res.redirect(__dirname + "/public/arena.html");
But, that isn't a URL at all. That's a path name on your local hard disk. res.redirect() sends a URL back to the browser and, if the browser is following redirects, it will then request that URL from scratch as a branch new request. So, you need to send a URL (not a path) and you need to send a URL that you have a route configured for that will serve the desired file.
It also looks like your express.static() statements might be incorrect. For us to help more specifically with those, we need to know where the static HTML files are on your hard drive relative to __dirname and we need to know exactly how you want the URLs for them to work. For example, do you want a request for /arena.html to serve __dirname + /public/arena.html? Is that what you are trying to do? Please explain that part so we can advise more specifically on your express.static() statements.
If that is the case, then you can change your redirect to:
res.redirect("/arena.html");
I'm attempting to store an object that my user clicks on in my server so that when the page changes, all the information from that object can be displayed fully in a profile page.
I'm unfamiliar with Angular $http but I've tried to write a call that will POST to the server, unfortunately when I scan through the req object in VScode I can't find where the object I sent is contained, so I can send it on to my function.
Controller function:
$scope.storeProfile = function(child){
$http.post('/storeTempProfile', child)
.then(function(response) {
window.location.href = 'DemoPage.html';
});
}
server.js:
app.post('/storeTempProfile', function (req, res) {
profileStorage.storeProfile(req);
});
does my app.post look right? And what property of req do I need to use the dot operator on to access my object? I can't seem to find the object data anywhere in req and that makes me thing there's something wrong with how I wrote app.post
It looks like you are using express. So in that case, you want to access the object on req.body, but this will require you use body-parser. The example on their homepage:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// create application/json parser
var jsonParser = bodyParser.json()
// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400)
// create user in req.body
})
You will notice in this example that they pass the json parser into the route itself. This is only necessary if you want to have different parsers for different routes. Usually you just want to set it to all routes, which you can do by using app.use(bodyParser.json()).
I'm currently getting started with Sails.js, and I want to add user accounts to my toy app, so I installed the "sails-auth" package that creates a Passport-based user authentication system. I can create new users by sending POST /user, and I can sign in with POST /auth/local.
The documentation says:
Authenticate with the local strategy via a POST to /auth/local with params identifier (email) and password). This will also create a session. See passport.local for more.
However, when I try to GET /user/me, which routes to a controller action that should return the current user in the session, the page instead gives an empty response. Why is this happening? Is there some kind of configuration step that I'm missing?
By the way, I haven't changed or messed around with the sails-auth package. It's still completely new; the "me" action looks like this:
me: function (req, res) {
res.ok(req.user);
}
EDIT: I've found a temporary workaround by searching the issues in the sails-auth repo. Instead of getting a user object from req.user, you can get a string user ID from req.session.passport.user.
Your me action as written is only going to return whatever you are passing in as the user param. Sails builds on top of Express.js so req is the request from the browser and res is the response to the browser.
Most likely you are sending the data to your me action in the req body which is why your response is blank, simply put, req.user is empty so the response is empty. In that case you would access it with req.body.user, you could also try var user = req.params();
For debugging and just generally getting a feel for how the req and res objects are structured I suggest you always start sails (in development, never in production) with the verbose flag.
sails lift --verbose
Then you can do this:
me: function(req, res){
sails.log.verbose(req);
res.ok(req.user);
}
And have it print out the entire req object so you know what's in req.user.
Typically though you would do a database lookup as the user param would be an id. Which means your me function might look (something, obviously depending on your dbc it might be pretty different) like:
me: function(req, res){
var userId = req.body.user;
User.find({'user_id': userId}.exec(function(err, user){
if(err){
//tell peeps there was an error
}else{
res.ok(user);
}
});
}
Best debugging for routes and for the request object:
'/*' : function(req, res, next) {
sails.log.verbose("method: ", req.method, "\n body: ", req.body, "\n url:", req.url);
next();
},
Just paste that at the start of your routes module.
I have a node express app , using express-stormpath for authentication/authorization
I have a GET route which is called with certain jquery parameters.
If the user is logged in everything is working as expected.
If not the user login screen is shown.
After stormpath authentication and authorization is done my query params are lost.
Is there any way to retain those?
app.get('/myRoute', stormpath.groupsRequired(['admin']), function(req, res){
console.log('req.query ',req.query);
//do somehting with the query data
res.sendStatus(200);
});
after authentication req.query is {}.
Any ideas?
Thank you for the question, I work at Stormpath and I'm more than happy to help. Our express-stormpath library is open source, and we're always happy to fix bugs and review pull requests.
Can you tell me which version of our library you are using? At the moment I'm not able to reproduce the problem you are seeing. Here is a quick example that I put together with the latest version, 3.0.1:
'use strict';
var express = require('express');
var stormpath = require('express-stormpath');
var app = express();
var port = process.env.PORT || 3000;
app.use(stormpath.init(app));
app.get('/admins', stormpath.groupsRequired(['admins']), function(req, res){
res.json(req.query);
});
app.on('stormpath.ready',function () {
console.log('Stormpath Ready');
});
app.listen(port, function () {
console.log('Server listening on http://localhost:' + port);
});
With this example, I do the following:
1.) Assert that I'm not logged in, by deleting all my cookies for localhost.
2.) Type /admin?foo=bar into the URL bar.
3.) I am redirected to the login page.
4.) I login with valid credentials.
5.) I am redirected to /admins?foo=bar, as expected, and I see the req.query object in the body of the page that is rendered. This is only true if the user is in the admins group, if they are not I will see the "Unauthorized" error message page.
Can you compare my steps and my example to your application, and let us know if there are any differences? Thanks!
I don't think that stormpath is removing query from request.
But we can check it by adding middlewhare before stormpath initialization:
var express = require('express');
var stormpath = require('express-stormpath');
var app = express();
// binding middleware to assign req.query to req.q param
app.use(function(req, res, next) {
req.QUERY = req.query;
next();
});
function restoreQuery(req, res, next) {
req.query = req.QUERY;
next();
}
app.use(stormpath.init(app, {
// Optional configuration options.
}));
app.get('/myRoute',
stormpath.groupsRequired(['admin']),
restoreQuery,
function(req, res){
console.log('req.query ',req.query);
//do somehting with the query data
res.sendStatus(200);
});