Redirecting client with NodeJS and Restify

泄露秘密 提交于 2019-12-04 16:51:20

问题


I'm building a REST backend for an SPA with NodeJS, Restify and PassportJS for authentication. Everything's working except the last step, which is redirecting the client from the backends /login/facebook/callback to the home page of the application.

I've searched online and found lots of answers for ExpressJS but nothing useful for Node-Restify yet. I've managed to pick up a few snippets of code and this is what I'm attempting at the moment:

app.get('/api/v1/login/facebook/cb', passport.authenticate('facebook', { scope: 'email' }), function(req, res) {
    req.session.user = req.user._id;
    res.header('Location', '/#/home');
    res.send();
});

The response is sent but the location header is not included and the client is presented with a white screen. How do I do a proper redirect using the Node-Restify API?


回答1:


Restify's Response interface now has a redirect method.

As of this writing, there's a test showing how to use it here.

The contents of that test are:

server.get('/1', function (req, res, next) {
    res.redirect('https://www.foo.com', next);
});

Many folks who use Restify are more familiar with ExpressJS. It's important to understand that (again, as of this writing) one of the three main public API differences affecting porting of Express plugins is that the res.redirect method in Restify requires you to pass next (or an InternalError is thrown). I've personally ported several modules from Express to Restify and the main API differences at first are (in Restify):

  • server.use is only for path & HTTP-method-agnostic middleware
  • res.redirect requires that you pass next
  • Some members or the Request interface are methods rather than values, such as req.path. req.path is an alias of req.getPath in Restify

I am NOT saying that under-the-hood they are similar, but that the above three things are the main obstacles to porting over Express plugins. Under-the-hood, Restify has many advantages over Express in my experience using it in both large enterprise applications and personal projects.




回答2:


You need to use redirection status code 302.

res.send(302); or res.send(302, 'your response');



来源:https://stackoverflow.com/questions/18613953/redirecting-client-with-nodejs-and-restify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!