1

I'm trying to use res.render() to pass data to a Pug template. When I get to this point in my code:

const _renderPage = function(req, res, responseBody) {  
console.log(responseBody);
res.render('page-template', {  
    pageData: responseBody,
    pageTitle: 'this is the about page!' }
    ); 
};

console.log(responseBody) shows:

[  { _id: '5bda4cfc11922d1dc5961922',
    name: 'about',
    body: 'about ksdjflskjflksdfks' }  ]

However, my Pug template which looks like the following, will not print the actual values of pageData.name or pageData.body even though it does print the pageTitle variable:

h1= pageTitle
p Welcome to #{pageData.name}

.row
  .col-12
    p #{pageData.body}
Graham
  • 7,431
  • 18
  • 59
  • 84
  • have you tried breaking just the stuff you want out, dropping the `pageData` variable altogether? ```js res.render('page-template', { {...responseBody}, pageTitle: 'this is the about page!' } ); }; ``` ```pug h1= pageTitle p Welcome to #{name} .row .col-12 p= body ``` – jayands Nov 02 '18 at 02:16
  • About the 304 part of your question's title - technically that's not an error (4XX are errors and 3XX are redirects), but that response makes sense on reloading the page and nothing has changed. If you're really interested, take a look at this: https://stackoverflow.com/questions/26166433/how-to-prevent-request-that-returns-304 – Graham Nov 02 '18 at 14:40

1 Answers1

2

Your root issue is that responseBody is an array, and you are trying to access it as an object.

Change the render function to feed the first element in the array to the template and it will work as expected:

res.render('page-template', {  
  pageData: responseBody[0],
  pageTitle: 'this is the about page!' }
); 
Graham
  • 7,431
  • 18
  • 59
  • 84
  • Thank you, that worked. I had copied over code that was used to act on an array of database items in a different template using "each x" and didn't adapt it properly for returning an array of only one item. I think I can further refine my API code (not shown) to use findOne() rather than find() and it will make more sense for this. – neongreensticker Nov 02 '18 at 14:38
  • Of course it's never THAT simple :) Read this first: https://blog.serverdensity.com/checking-if-a-document-exists-mongodb-slow-findone-vs-find/ – Graham Nov 02 '18 at 14:42
  • The simplest (and therefore the fastest running) solution is just to take the first element of the array. If the array returns as zero-length just make sure your error handling can pick that up and handle it appropriately. – Graham Nov 02 '18 at 14:46