Javascript 如何在Vue.js Express应用程序中设置路由参数

Javascript 如何在Vue.js Express应用程序中设置路由参数,javascript,node.js,mongodb,express,vue.js,Javascript,Node.js,Mongodb,Express,Vue.js,我正在尝试构建一个基本的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

我正在尝试构建一个基本的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();
    });
  });
});
在上面的快速路线中,我添加了
let id=req.params.id
,目的是提示该路线根据
req.params.id
响应特定的用户信息。我不确定如何进一步配置此路由以根据id实际返回此类信息。我尝试在路由中实现以下功能:

collection.find({u-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();
    });
  });
});

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

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

谢谢你的回复。请参见上述问题中更新的快速路线。我试图实现您所描述的,但在Vue组件
xhr.js?b50d:178 GET中的
GET
路径仍然出现错误http://localhost:3000/users/ 404(未找到)
快车似乎无法找到路线。如果还没有重新启动,则在路由之前和路由功能内部给它一个控制台日志req.params.id。它仍然找不到路由