json - Node.js/Express/Mongoose - 如何发送 JSON 和对象 View ?

标签 json node.js express mongoose

当我使用 Mongo 在 Node/Express 中显示模型对象时,我想将 JSON 对象与 View 一起传递。

当前路线(仅经过 View ):

app.get('/page/:customurl', function(req, res, next) {
  Page.findOne({ customurl: req.params.customurl.toLowerCase()}, function(error, page) {
    if (!page) return next(new NotFound('Document not found'));
    res.render('pages/page_show.ejs',
      { locals: {
          title: 'ClrTouch | ' + page.title,
          page:page,
      }
    });
  });
});

我可以将 pagejson:page.toObject() 添加到本地变量中,然后将 pagejson 放在我的页面上的某个位置吗?当我尝试时,它在浏览器中显示为 [object, Object]。有没有简单的方法将 JSON 传递到 View ?

谢谢!

最佳答案

您应该查看JSON methods

在 Node repl中:

> var document = {a: 'first property', b: 'second property'};
> JSON.stringify(document)
'{"a":"first property","b":"second property"}'
> 

如果您需要以不同的方式响应路由(例如通过 ajax 请求),您可以将新参数传递给 url app.get('/page/:customurl.:format', 。 .. 或检查存储在 req.headers

中的请求 header
if ( req.headers["HTTP_X_REQUESTED_WITH"] === "XMLHttpRequest" ) {
  res.send(document);
} else {
  res.render(...);
}

关于json - Node.js/Express/Mongoose - 如何发送 JSON 和对象 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7652942/

相关文章:

javascript - 按钮未重定向到正确的页面

xml - 如何使用 XSL 转义 XML 内容以将其安全地输出为 JSON?

c# - 在 ASP.Net MVC Controller 中,如何获得一种方法来识别来自 JSON 和 Form-urlEncoded 格式的数据?

python - 使用 node.js pm2 在虚拟环境中运行 python 脚本

javascript - 如何发送PDF文件到前端?

node.js - 从/提供静态文件

java - jQuery - JSON 填充下拉列表

json - Golang 结构解码 xss

javascript - 实现全面的快速路由解决方案后,获取 API 调用失败 : Unexpected token < in JSON at position 0

node.js - 运行 npm install 取消构建全局 npm