如何在 res.render EJS 模板之后制作 express return JSON?

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

我需要呈现页面并发送 json 响应快递 restful api。 我能够做一件事,或者另一件事,而不是两者。 这是我拥有的:

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

上面的代码正确地呈现了模板,但 return 没有任何 JSON 响应。

但是,为了渲染并获得 200 响应,我尝试了:

这是 returning:

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

这意味着它 returning json 但不是 ejs 模板 myTemplate.ejs

更新:我更新了我的答案以选中接受 header。浏览器不发送 application/json 所以代码给出 html,对于你发送 api 的调用 Accept: application/json 然后它返回 json

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});
       }
  })
})