Skip to content Skip to sidebar Skip to footer

Nodejs: Send A File And Data At Once

This is what I got. It works great but I'd like to be able to send a file and data (JSON), to the client when he logs in my website. Is there any way to combine that? app.get('/',

Solution 1:

You can't send 2 files at once. But you can embed the JSON inside the html by using a template library with ejs.

Solution 2:

A stream can send only one type of content for a request. However, depending on your Accept headers, you can send different content for different requests on the same request URL

app.get('/', function (req, res) {      
    if(req.accepts('text/html')){
        res.sendfile(__dirname + '/index.html');
        return;
     }
     elseif(req.accepts('application/json')){  
        res.json({'key':'value'});
        return;
     }
});

Here if your request header accepts 'text/html', it will return the index.html file. and if the request header accepts 'application/json' it will return the JSON response.

Post a Comment for "Nodejs: Send A File And Data At Once"