【问题标题】:How to set up route parameters in Vue.js Express app如何在 Vue.js Express 应用中设置路由参数
【发布时间】:2020-04-09 08:44:54
【问题描述】:

我正在尝试构建一个基本的 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();
    });
  });
});

【问题讨论】:

    标签: javascript node.js mongodb express vue.js


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回复。请参阅上述问题中的 UPDATED EXPRESS ROUTE。我尝试实现您所描述的内容,但 Vue 组件中的 GET 路由仍然出错
    • xhr.js?b50d:178 GET http://localhost:3000/users/<<route param id>> 404 (Not Found)
    • 似乎 Express 找不到路线。重新启动它,如果你还没有,在路由之前和路由函数内部还有一个控制台日志 req.params.id。
    • 还是没有找到路线
    猜你喜欢
    • 2020-06-16
    • 2015-07-05
    • 2020-06-17
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    • 2017-11-23
    • 2021-06-10
    相关资源
    最近更新 更多