首页 > 解决方案 > 如何在 Vue.js Express 应用中设置路由参数

问题描述

我正在尝试构建一个基本的 Vue.js Express 配置文件接口,该接口根据与每个用户关联的路由参数 id 返回特定用户的配置文件信息。Vue.js 中的.get()请求设置如下:

  created () {
    let uri = `http://localhost:3000/users/${this.$route.params.id}`;
    this.axios.get(uri).then((response) => {
      this.profile = response.data;
    });
  },

Express.js中对应的GET路由设置如下:

// mongodb
const mongo = require('mongodb').MongoClient;
const url = '...'; // connection url
const usersDB = 'users'; // users db name


app.get('/users/:id', function(req, res) {

let id = req.params.id;

  var users;
  const findUsers = function(db, callback) {
    const collection = db.collection('documents');
    // no query filter
    collection.find({}).sort( {username: 1} )
    .toArray(function(err, docs) {
      users = docs;
      callback(docs);
    });
  }
  mongo.connect(url, function(err, client) {
    // assert.equal(null, err);

    const db = client.db(usersDB);
    findUsers(db, function() {
      // send users
      res.status(200).send(users);
      client.close();
    });
  });
});

在上面的 Express 路由中,我添加let id = req.params.id的目的是提示该路由响应基于req.params.id. 我不确定如何进一步配置此路由以实际返回基于 id 的此类信息。我尝试在路线中实现以下内容:

collection.find({_id: mongo.ObjectId(req.params.id)})

而不是使用:

collection.find({}).sort( {username: 1} )

...但这没有用。知道如何设置此路由以基于返回数据req.params.id吗?谢谢!

更新的快速路线

// get all users
app.get('/users/:id', function(req, res) {

  var o_id = new mongo.ObjectID(req.params.id))
  // get all users
  var users;
  const findUsers = function(db, callback) {
    const collection = db.collection('documents');
    // no query filter
    collection.find({'_id': o_id})
    .toArray(function(err, docs) {
      users = docs;
      callback(docs);
    });
  }
  mongo.connect(url, function(err, client) {
    const db = client.db(usersDB);
    findUsers(db, function() {
      // send users
      res.status(200).send(users);
      client.close();
    });
  });
});

标签: javascriptnode.jsmongodbexpressvue.js

解决方案


由于 ObjectId 比较不起作用,似乎没有返回结果。使用 req.params 中的 id 创建新的 ObjectID,然后执行 collection.find 应该会带回结果

var o_id = new mongo.ObjectID(req.params.id);)
collection.find({'_id': o_id});

推荐阅读