Redirecting client with NodeJS and Restify
Asked Answered
S

2

15

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?

Strapped answered 4/9, 2013 at 12:34 Comment(0)
T
21

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.

Taler answered 5/9, 2015 at 0:50 Comment(2)
Accepting this as its more in line with intended use of RestifyStrapped
For whatever reason, with Restity 4.3.0, I had to include the protocol https://www.foo.com otherwise it would just redirect the path only.Tempered
J
11

You need to use redirection status code 302.

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

Jacktar answered 4/9, 2013 at 14:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.