gpt4 book ai didi

javascript - NodeJS : how to use arguments like req, res,函数结果?

转载 作者:搜寻专家 更新时间:2023-11-01 00:27:17 25 4
gpt4 key购买 nike

我对 JS 很陌生,尤其是 Node 和 Express。我正在学习一些关于如何构建 API 的教程,同时学习 JS 的特殊功能,例如 let/const/var、箭头函数等。

在很多教程中我都看到过这样的事情:

somecode.then((result) => {someothercode})

例如:“somecode”是一个获取请求

“result”是返回值的名称还是 JS 开发人员使用的约定?我的意思是,这是否有效?

somecode.then((foo) => {someothercode})

还有req,res变量是什么意思?

app.get("/users/:userId", [
usersController.getById
]);

这里是 getById 函数(再次使用“结果”):

exports.getById = (req, res) => {
userModel.findById(req.params.userId).then((result) => {
res.status(200).send(result);
});
};

Controller 中定义的getById方法需要(req, res),这是否意味着当我像上面的代码那样调用它时,隐式使用了req和res参数?

还需要一个参数:

req.params.userId 

在路由的url中,它如何传递到另一个文件?我有一个 route.js 文件,它使用一个使用 model.js 的 controller.js 文件。参数如何从路由到 Controller ?

如果我更改参数名称,它不会起作用,对吗?例如:

req.params.id

抱歉发了这么长的帖子,我正在尝试理解 JS 逻辑以养成良好的习惯并编写干净的代码。

谢谢!

最佳答案

Is "result" the name of the returned value or is it a convention that JS developper use? By that I mean, does this for example work?

根据我的经验,是的 - result 经常被使用。通常您会看到诸如 valueresponse 之类的东西,但最终它可以是您定义的任何内容。我会建议坚持惯例,并查看 MDN Promise tutorial如果您刚开始了解 NodeJS 异步操作。

Also for req, res variables what does this mean?

app.get("/users/:userId", [
usersController.getById
]);

那是一个中间件链。查看Express docs获取更多信息。

the getById method defined in the controller needs (req, res), does that mean, when i call it like the code above, the req and res arguments are implicitly used? Also it needs a parameter :

req.params.userId 

which is in the url It won't work if I change the param name right? for example:

req.params.id

是的,那是使用命名参数。没有完整的路由器代码,很难知道 getById 方法是如何链接到定义的路由的。 Express routing documentation这可能是一个好的开始。

关于javascript - NodeJS : how to use arguments like req, res,函数结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56656411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com