Node.js 如何传递变量以获取请求
我有一个调用get请求的函数:Node.js 如何传递变量以获取请求,node.js,mongodb,express,Node.js,Mongodb,Express,我有一个调用get请求的函数: confirmUser(username: string) { this.http.get<{ users: User[] }>('http://localhost:3000/users').subscribe( // success function (response) => { this.user = response.users; console.log(this.user); } ), (error: any) =&
confirmUser(username: string) {
this.http.get<{ users: User[] }>('http://localhost:3000/users').subscribe(
// success function
(response) => {
this.user = response.users;
console.log(this.user);
}
),
(error: any) => {
console.log(error);
}
}
username的值来自表单字段,因此调用它的组件不会订阅任何URL参数,如果这会造成差异。如果将其作为参数传递,则应使用
req.params
,否则req.query
进行查询字符串
使用参数(即:http://localhost:3000/users/grok
):
使用查询字符串(即:):
非常感谢你。我今天盯着这个看太久了。
router.get('/', (req, res, next) => {
// User.find().then(users => {
User.findOne({username: "Grok"}, {} ).then(users => {
res.status(200).json({
users: users
});
})
.catch(error => {
returnError(res, error);
});
});
router.get('/:username', (req, res, next) => {
// User.find().then(users => {
User.findOne({username: req.params.username }, {} ).then(users => {
res.status(200).json({
users: users
});
})
.catch(error => {
returnError(res, error);
});
});
router.get('/', (req, res, next) => {
// User.find().then(users => {
User.findOne({username: req.query.username }, {} ).then(users => {
res.status(200).json({
users: users
});
})
.catch(error => {
returnError(res, error);
});
});