Search code examples
node.jsexpresscontent-type

Serve both text and image data when rendering a template?


Trying to send both text and image data as local variables to a server-side rendered page using templates.
I know I have to set the Content-Type as 'image/png'.
How can I set the Content-Type for one variable when all the other variables are text?
Thank you so much!

res.render('profile.html', { locals: {
  tasks: tasks,
  msgExists: '',
  name: req.user.name,
  email: req.user.email,
  photo: req.user.photo //how to set Content-Type for this variable?
}});

Solution

  • the template is rendered on server side, and then sent to client. this means the content type of the response is "text/html", not "image/png".

    your variables do not have "Content-Type", as they are not HTML responses. if you want to embed an image in an html, and you know its raw data, it usually looks like this:

    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="/>
    

    now if you have the image data (like whatever after base64 part) somehow stored in a JS variable, and want to pass it to your template renderer to embed that image in the resulting html, it would look like this:

    // node js code:
    imgData = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
    res.render('my.template.html', {
      imgData, 
      // whatever else ...
    });
    
      <!-- template code: -->
    
      <img src="data:image/png;base64,{{imgData}}"/>
    
      <!-- whatever else -->
    

    of course this can change a bit based on the exact format you are storing the image data.