Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including JSON in Node.js res.redirect()

What specific changes need to be made to the code below so that the JSON contents of the message variable can be sent from the Node.js server to the AngularJS client?

The following code is in the routing file of a Node.js app. The code below generates JSON and then redirects control to the redirectURL='/' handler, which sends the ./public/index.html file to the AngularJS client.

It is important that the JSON message be sent to the AngularJS client in this transaction, so that the AngularJS browser app can be responsible for preserving the user's unique identity. That way, subsequent requests from AngularJS browser apps can be served by any of hundreds of clones of this Node.js app, and each clone will use the JSON that it receives with each request to connect with a Redis cluster to manage user identity across multiple requests. This will enable Node.js to not have to remember user identities.

app.get('/some_endpoint', function(req, res) {
    var redirectURL = '/';
    request.post(otherServerUrl, function(err, response, body){
        if(err){console.log('ERROR with token request.')}
        var data = JSON.parse(body);
        getUser(data.access_token).then(function(message) {
            console.log('in callback, jwtJSON is: ');console.log(message);
            res.redirect(redirectURL);
        });
    });
});

app.get('*', function(req, res) {
    res.sendfile('./public/index.html'); // load the single view file (angular will handle the front-end)
});

Note that the app.get('*', function(req, res) needs to be able to also serve requests from users that have not been redirected from app.get('/some_endpoint', function(req, res) and who thus do not have any message JSON at the server to be sent to the browser app.

like image 756
FirstOfMany Avatar asked Jan 06 '23 16:01

FirstOfMany


1 Answers

If what you're trying to do is to pass information to a page that will be loaded from a redirection, then the usual way to do that is to encode the information as query parameters on the redirect URL.

This will get passed through the redirect to the newly loaded page and that page can then parse the query parameters to grab the information.

It is also possible to put information into a cookie before the redirect and have the redirected page get info from the cookie, but if you are using different domains during the redirect process, the cookie can be complicated or impractical (since cookies are associated with a specific domain).

You can't just return JSON with the redirect response because a redirect will not pass the JSON on to the redirected page - that's not how redirects work. A redirect just loads the page that corresponds to the new URL.

like image 131
jfriend00 Avatar answered Jan 08 '23 08:01

jfriend00