3

I have to serve a html file with express, but also want to send an object along with the response. How can i send both - the detail.html and the object 'car' - and how can i access it at the client side?

app.get('/unit/:id', function (req, res) {
console.log(req.params.id)
var car = {type:"Fiat", model:"500", color:"white"};
res.sendFile(__dirname + '/detail.html', car);
});
Patrick
  • 6,537
  • 1
  • 13
  • 7

2 Answers2

2

res.sendFile has to set some special headers (Content-Disposition paired with a Content-Type) so the browser will understand that an attachment its comming and based on the file type and browser either show the save dialog or open the file

What you could do is send the car object as a json with res.json and in the frontend check that the json was fetched so you can hit a second endpoint which will trigger the download

eltonkamami
  • 5,134
  • 1
  • 22
  • 30
2

Not really sure about your current setup but you might want to restructure your express app a little. You need to define a view engine and use

res.render('someview', dataObject);

http://expressjs.com/en/api.html#res.render

with ejs:

app.set('view engine', 'ejs');  

route:

app.get('/', function(req, res) {  
  res.render('index', { title: 'The index page!' })
});

html:

<div>  
    <%= title %>
</div>  
user1695032
  • 1,112
  • 6
  • 10
  • in this case i would like to avoid using the template-engine and render the plain html. – Patrick Feb 15 '16 at 20:59
  • if that's the case, you can't do anything with the Object in the view. That's what template engines are for. look at this for example: https://github.com/ericf/express-handlebars . They basically build the template before it's sent to the client. You would have to come up with some hybrid workaround otherwise. – user1695032 Feb 15 '16 at 21:02
  • okay, let´s assume i am using ejs engine to render the HTML. how do i receive the object at the frontend? how does my javascript have to look like. i have no clue... – Patrick Feb 15 '16 at 21:25
  • edited my answer. Took the example from here: http://robdodson.me/how-to-use-ejs-in-express/ – user1695032 Feb 15 '16 at 21:31