简体   繁体   English

Node.js 相当于 ASP.NET MVC 中的控制器是什么?

[英]What is the Node.js equivalent to a controller in ASP.NET MVC?

I have experience programming in ASP.NET MVC.我有 ASP.NET MVC 编程经验。 I am learning how to use Node.js, but I am a little confused on what a controller would look like in Node.js.我正在学习如何使用 Node.js,但我对 Node.js 中控制器的外观有些困惑。

What would the below code look like in Node.js?下面的代码在 Node.js 中会是什么样子?

[HttpGet]
public Json GetMyResults(){
    //query to database 
}

[HttpPost]
public Json SubmitResults(){
    //query to database 
}

In NodeJS the abstraction for the controller is defined by the Framework you choose to use.在 NodeJS 中,控制器的抽象由您选择使用的框架定义。

For example, in Express your controller is just a plain function with two or three arguments.例如,在 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);

  })

});

A lot of popular frameworks are express-based or inspired, so this will be a common structure in other projects such SailsJS .许多流行的框架都是基于 express 或启发的,因此这将是其他项目(例如SailsJS )中的常见结构。 For more information on Express checkout the official website .欲了解更多快捷结账信息,请访问官方网站

An issue you will run into is that ASP.NET is a platform with a great deal "baked in".您将遇到的一个问题是 ASP.NET 是一个有很多“内置”的平台。 Node is an environment which is much more flexible. Node 是一个更加灵活的环境。 A common web server library is Express.一个常见的 Web 服务器库是 Express。 See an Express tutorial for the answers to your question.有关问题的答案,请参阅 Express 教程。

I have generally found the Scotch IO tutorials to be quite helpful我通常发现Scotch IO 教程非常有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM