I'm working on a little project - completely new to this stuff - and hope you can help me out.
On the base of this project https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4 which is up running and works really great.
The main goal is it to send a UserID over the network - which is already working by python/json - and let the server react on this and show a login with the just sent UserID and an password input.
I already enhanced the server.js with a POST from the python script and when the server is running the terminal recognizes when the UserID is sent.
...
router.route('/bears/:id')
.get(function(req, res) {
Bear.find({‚id': req.params.id}, function(err, bear) {
if (err)
res.send(err);
console.log(‚here i am ...');
});
});
...
I also created a HTML which I thought should always listen (by AJAX) to the post and if the trigger (UserId) is send it should forward to another side with the input field.
So right now I don't really know how to implement that the Server already got the trigger and the HTML forwards the User to the Login?
Let the server handle where the user goes - issuing a 200 for a successful user, or an error 400 if it's a bad request. For example:
router.route('/bears/:id')
.get(function(req, res) {
Bear.find({‚id': req.params.id}, function(err, bear) {
if (err)
res.status(400).send(err); //Send a generic bad request error
else {
res.status(200).render('login', { name: req.params.id }); //Direct client to your login page (this example uses the jade template egine)
});
});
I hope this is what you're looking for :)
Related
I have an express with sequelize (using postgres) REST backend server. When I post a create request from my client the database entry is created then a afterCreate hook is running a processing script for a second or so. This is running fine using the afterCreate hook form sequelize.
Subsequently I need to let the client know the processing is ready, upon which the client will run some process of its own. How do I message to the client?
I'm not a Node expert and my answer might be wrong, but based on the https://groundberry.github.io/development/2016/11/06/continue-building-your-node-app-with-express-and-sequelize.html couldn't you do the following:
router.post('/', function(req, res) {
//node return reply after running the create
return models.User.create({ username: req.body.username }).then(function() {
return res.json({ message: 'New user created' });
});
});
(When I run same code on ubuntu with node 4.2.6. I don't see this problem. )
I found some has similar problem: Express.js close response
==============problem description=========================
I encountered a very strange problem.
In my Express project, I am using passport package.
As long as I signed in myself, then every page will keep loading for 2 minutes.
If I am not logged in, I found pages behave normally.
/* GET home page. */
router.get('/', function (req, res, next) {
res.render('index', {
title: 'FASIDS',
activePage:'Home',
isAuthenticated: req.isAuthenticated(),
user: processReqUser(req.user)
}, function (err, html) {
if (err) {
next(err);
return;
}
res.send(html);
});
});
I have to substitute res.send(html) with res.end(html) to make my code behaves normally in both situations ("signed in" or "not signed in").
Really have no idea how to deal with it. Please help.
Additionally, please refer my processedPassport.js to see how I am handling authentication.
The passport is used in app.js as following:
...irrelevant code..
var passport = require('./components/processedPassport.js').addPassport(app, db_models);
...irrelevant code....
For reference, I included screenshots
Following pic shows a loading time of 2 mins
Following pic shows request and response headers
Is there any way how to communicate between those two?
Lets say i have a server.
Someone uploads a file , the server process the file and find that its incorrect and send event to the client. The client catch the event and does some DOM manipulation displaying fancy styled error message.
Is something like that possible?
Yes - of course this is possible. Since you have tagged your question with javascript and nodeJS, I'll show you one example with javascript for the server, i.e. nodeJS.
It uses callback functions for routes. This allows you to do just what you describe, build logic into any given request. Below is a standard route request from a user to login, you can see below that there is a simple 'if' statement which will execute code if 'something went wrong' and return a message to the user. Take a look:
app.post('/login', function(req, res, next){
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.send({error : 'something went wrong :('}); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.send({success:'success'});
});
})(req, res, next);
})
I'm currently working on a angular + sails project. I'm using json web tokens for auth. It works fine but I wanna set a new token for every validated request that my angular app does.
This is my auth policy
passport.authenticate('jwt', function (error, user, info) {
if (error) return res.serverError(error);
if (!user)
return res.send({
message: info.message,
code: info.code,
tokenError: info.name
});
// The token is ok past this line
// I check the user again
User.findOne({ email: user.email }, function (err, thisUser) {
if (err) { return res.send(err); }
if (!thisUser) {
// send a bad response
}
req.user = user;
// This is the new token that I wanna send to the frontend
var newToken = AuthService.createToken(thisUser);
next();
});
})(req, res);
With this policy I can create the new token, but then I would need a way to include this token in every response, this Is the point where I'm stuck.
I gues I could do it manually in every controller action, but this is want I want to avoid
The best way to standardize your responses in Sails is to use the custom responses feature. In short, instead of calling res.send() or res.json() in your controller actions, call res.ok() instead, and then customize the api/responses/ok.js file that is generated with every new Sails app. This is the same response that Sails blueprints use as well!
In your case, you'd want to save the token onto the request object (e.g. req.token) in your policy code, then use that property in your logic inside of ok.js.
I'm trying to build a simple application with parse.com as my user manager.
I would like to make a login call to parse.com from my client side, and call my node.js server with the user's session token (I'll add it as a cookie). In the server side, I'll validate the session (using https://parse.com/docs/rest#users-validating) and allow access only if the session is valid.
For example (in my server):
app.get('/api', function(req, res, next) {
var token = getTokenFromRequest(req);
if(tokenIsValid(token)) {
next();
} else { // Redirect... }
});
app.get('/api/doSomething', function(req, res) {
// Do something....
});
the tokenIsValid(token) function should be implemented using https://parse.com/docs/rest#users-validating.
However, it seems that the REST API user validation returns the user even if the user is logged out (expected to return 'invalid session').
Is this a bug in the REST API user validation? What am I doing wrong? Is there a better way for doing that?
Thanks!
Via REST there's no concept of sessions really. REST calls are meant to be stateless meaning that the (current) user at /me will be serialized from the token provided. If the token is associated to a user it will return the JSON representation of that user otherwise in returns an error.
One way or another that call is asynchronous so you can't really use it in and if statement.
You can do:
app.get('/api', function(req, res, next) {
var token = getTokenFromRequest(req);
serializeUserFromToken(token,function(err,parseResponse) {
if(err) return next(err)
if(parseResponse.code && parseResponse.code === 101){
// called to parse succedded but the token is not valid
return next(parseResponse);
}
// parseResponse is the current User.
next();
});
});
Where serializeUserFromToken makes a request to Parse with the token in the X-Parse-Session-Token header field.