简体   繁体   中英

How can I make express return JSON after res.render EJS template?

I need to render a page and send json response express restful api. I was able to do one thing, or the other, not both. Here's what I have:

app.get('/', (req, res) => {
  db.collection('myDatabase').find().toArray((err, result) => {
    if (err) return console.log(err)
    res.render('mytemplate.ejs', {myDatabase: result})
  })
})

The code above renders the template correctly but doesn't return any JSON response.

However, to render and have a 200 response I tried:

我试过的

Here is what is returning:

{ "htmlContent": {}, "status": "200" }

This means it's returning json but not the ejs template myTemplate.ejs

UPDATE: I have updated my answer to check Accept header. Browser does not send application/json so the code gives html, for your api calls you send Accept: application/json then it gives json back

let ejs = require('ejs');

app.get('/', (req, res) => {
  db.collection('myDatabase').find().toArray((err, result) => {
    if (err) return console.log(err)

       if(req.header('Accept').includes('application/json')){
        res.send(result);
       }else{
        res.render('mytemplate.ejs', {myDatabase: result});
       }
  })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM