[英]Accessing url parameters in sails action
I have a sails app, and I am agttempting to load a page with some data from a database, based on the id
of the recipe
model. 我有一个sails应用程序,并且我正在尝试根据
recipe
模型的id
从数据库中加载一些数据。
I have the route 'GET /recipes/single-recipe/:id': { action: 'recipes/view-single-recipe' }
set up, and am accessing the url http://localhost:1337/recipes/single-recipe/5b8c169936f1df3439fa39c7
我已经设置了路由
'GET /recipes/single-recipe/:id': { action: 'recipes/view-single-recipe' }
,并且正在访问URL http://localhost:1337/recipes/single-recipe/5b8c169936f1df3439fa39c7
In my view-single-recipe
action I'm attempting to load the recipe with the id of the URL parameter by accessing req.param('id')
but req
is showing undefined. 在我
view-single-recipe
操作中,我试图通过访问req.param('id')
来加载带有URL参数ID的配方,但是req
显示未定义。
//view-single-recipe.js module.exports = { friendlyName: 'View single recipe', description: 'Display "Single recipe" page.', exits: { success: { viewTemplatePath: 'pages/recipes/single-recipe' } }, fn: async function(inputs, exits) { const recipe = await Recipe.find({ id: req.param('id') //req undefiend }); // Respond with view. return exits.success({ recipe: recipe }); } };
Getting error: error: Sending 500 ("Server Error") response: ReferenceError: req is not defined
得到错误:
error: Sending 500 ("Server Error") response: ReferenceError: req is not defined
How can I load the correct recipe using the url param? 如何使用url参数加载正确的配方?
If you have the route /recipes/single-recipe/:id'
, then the " id
" from the URL path will be available as req.params.id
. 如果您具有路由
/recipes/single-recipe/:id'
,则URL路径中的“ id
”将作为req.params.id
可用。 Otherwise, it defaults to {}
For more info 否则,默认为
{}
有关更多信息
UPDATE: 更新:
But when it comes to Actions and Controllers , Sails.js
uses the machine-as-action
module to automatically create route-handling
functions out of machines like the example shows. 但是当涉及到Actions和Controllers时 ,
Sails.js
使用machine-as-action
模块自动从机器中创建route-handling
功能,如示例所示。 See the machine-as-action docs for more information . 有关更多信息,请参见“机器即操作”文档。
Note that machine-as-action provides actions with access to the request
object as this.req
instead of just req
, otherwise, there'll be a server error of req is not defined
. 请注意,机器动作为操作提供了对
request
对象的访问权限,就像this.req
而不是req
,否则,将存在req is not defined
的服务器错误。 So, for future references don't forget the this
keyword. 因此,对于将来的引用, 请不要忘记
this
关键字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.