【问题标题】:What is the Node.js equivalent to a controller in ASP.NET MVC?Node.js 相当于 ASP.NET MVC 中的控制器是什么?
【发布时间】:2017-02-10 04:29:57
【问题描述】:
我有 ASP.NET MVC 编程经验。我正在学习如何使用 Node.js,但我对 Node.js 中的控制器是什么样子感到有些困惑。
以下代码在 Node.js 中会是什么样子?
[HttpGet]
public Json GetMyResults(){
//query to database
}
[HttpPost]
public Json SubmitResults(){
//query to database
}
【问题讨论】:
标签:
c#
asp.net
asp.net-mvc
node.js
asp.net-mvc-4
【解决方案1】:
在 NodeJS 中,控制器的抽象由您选择使用的框架定义。
例如,在 Express 中,您的控制器只是一个带有两个或三个参数的普通函数。
app.get('/users/find', function(req, res) {
//
// The 'req' object contains the request input information
//
// This will access the id in query param
// Ex: /users/find?id=12345
//
var userId = req.query.id;
// Then you'll find it in your database
Users.findOne({id: userId}).then(function(user) {
// The 'res' object holds the methods for serving responses
//
// Serve a JSON as response with user information
res.json(user);
})
});
许多流行的框架都是基于 express 或灵感的,因此这将是其他项目中的常见结构,例如 SailsJS。
有关 Express 结帐的更多信息,请查看official website。
【解决方案2】:
您会遇到的一个问题是 ASP.NET 是一个具有大量“内嵌”功能的平台。 Node 是一个更加灵活的环境。一个常见的 Web 服务器库是 Express。有关您的问题的答案,请参阅 Express 教程。
我普遍认为Scotch IO tutorials 很有帮助