node.js - 使用 express 和 mongodb 提供动态 URL

标签 node.js mongodb url express

我正在构建一个具有类似 reddit 功能的网站。我希望用户提交的内容有自己的页面。每个提交都分配了一个 5 个字符的 ID,我希望它位于该页面的 URL 中。

我在路由器文件中有这个函数,它呈现一个名为 titles 的页面:

exports.titles = function(req, res){
i = 0
read(function(post){
    url = post[i].URL;
    res.render('titles', {title: post[i].title, url: post[i].URL});
});

};

它由 app.js 中的以下语句提供:

app.get('/titles', home.titles); //home.js is the router file

标题页面有一个带有文本 post.title 和 URL post.URL 的链接。当用户单击链接(例如 domain.com/12345)时,他们应该被带到一个名为 content 的页面,其中包含内容 post.body。

我如何 a) 将 URL 传回我的 app.js 文件以包含在 app.get 中,b) 在此路由器文件中包含 app.get 函数,或 c) 以任何其他方式解决此问题?

编辑:我确实有一个对象“标题”,它是一个 mongodb 集合,但它位于不同的模块中。没有理由我不能将它添加到路由器。

编辑:我尝试将其添加到 app.js 以查看它是否有效:

app.get('/:id', function(req, res){
  return titles.findOne({ id: req.params.id }, function (err, post) {
    if (err) throw(err); 

    return res.render('content', {title: post.title, content: post.body});
   });
});

编辑:我让它工作了。我所做的只是格式化标题,使其看起来像 domain.com/titles/12345 并将 app.get('/:id', 更改为 app.get('/titles/:id, ...

最佳答案

如果我猜对了,我会反过来做。

精简版

  1. 我将从 URL 中获取 id
  2. 然后我将从数据库中提取与此 id
  3. 关联的数据
  4. 并使用这些数据构建最终页面。

您不需要为每个 URL 创建新的路由。一个 URL 可以包含一些变量(这里是 id),Express 可以解析 URL 以获得这个变量。然后从这个 id 中,您可以获得构建正确页面所需的数据。

长版

我假设有人输入这个 URL:http://domain.com/1234
我还假设您有一个变量 titles,它是一个 MongoDB 集合。

你可以像这样定义一个路由:

app.get('/:id', function(req, res) {
  // Then you can use the value of the id with req.params.id
  // So you use it to get the data from your database:
  return titles.findOne({ id: req.params.id }, function (err, post) {
    if (err) { throw(err); }

    return res.render('titles', {title: post.title, url: post.URL /*, other data you need... */});
  });
});

编辑

我根据最后的评论做了一些修改...

关于node.js - 使用 express 和 mongodb 提供动态 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13747740/

相关文章:

node.js - Sequelize – 保存不足的时间戳

node.js - 具有单个文档字符串数组字段的服务器端分页

url - 由模式 ID 填充的 SVG 路径不适用于非根 URL

node.js - Node TLS 客户端中出现神秘 TCP 错误

java - Node HMAC 结果不同于 Ruby 和 Java

node.js - 从 axios 获取对象数组并使用返回值调用另一个 axios 函数并将输出附加到第一个结果

ruby-on-rails - 我应该学习哪种 MongoDB DSL?

javascript - 是否应该发布 MongoDB 插入/更新/更新/删除?

python - 用指向 URL 的链接替换文本中的 URL

php - 基本网址和基本链接网址有什么区别?