Express GET路由不适用于参数 [英] Express GET route will not work with parameters

查看:94
本文介绍了Express GET路由不适用于参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Express和猫鼬的新手.我目前正在做我的第一个项目,不是教程,所以遇到了问题.

I am new to Express and Mongoose. I am currently working on my first project, that is not a tutorial, and I has run into a problem.

我有多个路由,它们在index.js中定义如下:

I have multiple routes, they are defined in the index.js like this:

app.use('/api/client',require('./routes/client'));
app.use('/api/host',require('./routes/host'));

在路线中,有多个可使用的动词,例如PUT和POST. 这是有问题的路线(我正在尝试做的事情比这里介绍的要多,但这里介绍的效果不佳):

In the routes, there are multiple verbs that work, like PUT and POST. Here is the problematic route (I am trying to do more that what is presented here, but what is presented here, does not work as well):

router.get('/ama/:id', function (req, res, next) {
    Ama.findById(req.params.id).then(function(Ama){
        res.send(Ama);
    });
});

这应该起作用,对吗?它应该使用该ID返回数据库中的文档.而且我检查了文档是否存在,大概是100次. 现在,如果我大大简化了路由,删除了id,并做出了简单的响应,则该路由有效:

This should work, right? It should return the document in the database, with that id. And I have checked if the document excists, probably around a 100 times. Now, if I simplify the route greatly, removing the id, and make a simple response, the route works:

router.get('/ama', function (req, res, next) {
    res.send({type:"GET"});
});

太奇怪了,以至于我一旦添加参数,就会得到一个:

It's so wierd, that as soon as i add the parameter, i get a:

<pre>Cannot GET /api/host/ama</pre>

在邮递员中.

有什么想法吗? Mongod正在运行,我的其他路线正在运行.

Any ideas? Mongod is running, my other routes are working.

推荐答案

您似乎正在尝试检索以下URL:

It looks like you're trying to retrieve this URL:

/api/host/ama?id=SOMEID

但是,您为URL声明了一条路由,如下所示:

However, you have a route declared for URL's that look like this:

/api/host/ama/SOMEID

换句话说,id是URL路径的一部分,并且不作为查询字符串参数传递(这就是/:id的含义:它是路由应匹配的URL的一部分的占位符).

In other words, the id is part of the path of the URL, and not passed as a query string parameter (that's what /:id means: it's a placeholder for a part of the URL that the route should match).

因此,可以通过将id添加到路径(/api/host/ama/58e395a8c6aaca2560089c‌​e7)来更改请求URL,或者将路由处理程序重写为类似这样的内容:

So either change the request-URL by adding the id to the path (/api/host/ama/58e395a8c6aaca2560089c‌​e7), or rewrite your route handler to something like this:

router.get('/ama', function (req, res, next) {
    Ama.findById(req.query.id).then(function(Ama){
        res.send(Ama);
    });
});

但是,我建议使用前者(使id成为URL的一部分).

However, I would advise using the former (making the id part of the URL).

这篇关于Express GET路由不适用于参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆