在 sails 操作中访问 url 参数
Accessing url parameters in sails action
我有一个 sails 应用程序,我正在尝试根据 recipe
模型的 id
从数据库中加载一些数据的页面。
我设置了路由 'GET /recipes/single-recipe/:id': { action: 'recipes/view-single-recipe' }
,正在访问 url http://localhost:1337/recipes/single-recipe/5b8c169936f1df3439fa39c7
在我的 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
});
}
};
获取错误:error: Sending 500 ("Server Error") response:
ReferenceError: req is not defined
如何使用 url 参数加载正确的配方?
如果您有路线 /recipes/single-recipe/:id'
,则“id
" 来自 URL 路径将作为 req.params.id
提供。否则默认为 {}
For more info
更新:
但是说到Actions and Controllers,Sails.js
使用machine-as-action
模块自动创建route-handling
的功能类似于 example shows. See the machine-as-action docs for more information.
请注意,机器即动作为动作提供了对 request
对象的访问权限,如 this.req
而不仅仅是 req
,否则,将出现服务器错误 req is not defined
。因此,为了将来参考 不要忘记 this
关键字。
我有一个 sails 应用程序,我正在尝试根据 recipe
模型的 id
从数据库中加载一些数据的页面。
我设置了路由 'GET /recipes/single-recipe/:id': { action: 'recipes/view-single-recipe' }
,正在访问 url http://localhost:1337/recipes/single-recipe/5b8c169936f1df3439fa39c7
在我的 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
});
}
};
获取错误:error: Sending 500 ("Server Error") response:
ReferenceError: req is not defined
如何使用 url 参数加载正确的配方?
如果您有路线 /recipes/single-recipe/:id'
,则“id
" 来自 URL 路径将作为 req.params.id
提供。否则默认为 {}
For more info
更新:
但是说到Actions and Controllers,Sails.js
使用machine-as-action
模块自动创建route-handling
的功能类似于 example shows. See the machine-as-action docs for more information.
请注意,机器即动作为动作提供了对 request
对象的访问权限,如 this.req
而不仅仅是 req
,否则,将出现服务器错误 req is not defined
。因此,为了将来参考 不要忘记 this
关键字。