javascript - 如何在 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();
});
});
});
解决方案
由于 ObjectId 比较不起作用,似乎没有返回结果。使用 req.params 中的 id 创建新的 ObjectID,然后执行 collection.find 应该会带回结果
var o_id = new mongo.ObjectID(req.params.id);)
collection.find({'_id': o_id});
推荐阅读
- ios - 如何在 Swift 中使用 URLSession 添加 UIActivityIndicatorView?
- debian - 如何修改 Debian 源代码包以包含附加的可执行脚本?
- python - 使用 Pandas 对价值和时间指数进行下采样或平均数据
- notepad++ - 如何在记事本++中执行某个功能
- javascript - React/Electron 中的“SyntaxError:无效的正则表达式标志”
- java - 如何显示蓝牙设备列表然后连接?是否可以扫描与特征匹配的设备并连接到它?
- python-3.x - 将字符串部署到matplotlib时,如何将字符串中的一个单词加粗?
- c# - MVC 实体框架回滚不起作用
- excel - 从按钮分配/运行宏代码,无需在 Excel VBA 中使用单独的宏
- amazon-web-services - AWS '实例在降级的硬件上运行。' 关于我的软件