CVO
CVO

Reputation: 742

Nodejs Express send res.render and res.json simultaneously

How can I send res.render and res.json simultaneously in NodeJS with Express. I wanted something like:

app.get(basePath, function (req, res, next) {
    //More stuff
    res.json({token: token});
    res.render(path.join(publicPath, '/main'), 
        {mv: mv});
});

but it only gives me the token without rendering the page. Using this method:

app.get(basePath, function (req, res, next) {
    //More stuff
    res.render(path.join(publicPath, '/main'), 
    {mv: mv, token: token});
});

I don't have access to token param (I have to store it in client)

The idea is to avoid to use 2 requests (one for page testing the token and one for generate new token rtesting the old one). And avoid to have a hidden span with the token in every views.

Upvotes: 1

Views: 2544

Answers (2)

Şivā SankĂr
Şivā SankĂr

Reputation: 2036

HTTP uses a cycle that requires one response per request. When the client sends a request the server should send only one response back to client. So that you need to send only one response to the client either res.render() or res.json().

If you like to set some data like authentication token, you can set on your header using res.set() or res.header(). documentation

app.get(basePath, function (req, res, next) {

    //More Stuff ...

    res.header('token', JSON.stringify({ token: 'token' })); //use encrypted token
    res.render(path.join(publicPath, '/main'), { mv: mv });
});

To set header for all routers or particular set of router you can use middleware

Upvotes: 3

Matei Adriel
Matei Adriel

Reputation: 94

1) use a middleware to generate the token 2) quick tip, {token:token} is the same as {token}

Upvotes: 1

Related Questions