Express
Just as ASP. NET MVC has the same status as the best MVC framework under the. Nets platform, Express has the same importance in the node. JS Environment. On the Baidu "Nodejs Express" will run out a lot about how to use the development of Express to develop MVC articles, the same content here I do not want to repeat the story, about the beginning of the express article everyone to Baidu search on the good. This is just an essay, not a tutorial, but I want to use ASP. NET MVC and express to make some comparisons on what they are good at, to see what we can do as developers, and which ones are more beneficial to us.
Express and OWIN
OWIN Full Name: Open Web Interface for. NET, is a set of independent application frameworks that allow you to create a standalone runtime environment in IIS that can be configured on demand. I don't know if my explanation is accurate, more content can be consulted: "Getting Started with OWIN and Katana" and Katan items on CodePlex. The simple point of understanding is that you can configure the functionality of your web by configuring some of the existing "middleware (Middel Ware)" In a boot file with pure code. Let's look at a piece of code that is intercepted from ASP. The middleware that joins a log to the website to implement the log record
Log Middleware Implementation
Public classloggermiddleware:owinmiddleware{Private ReadOnlyILog _logger; PublicLoggermiddleware (Owinmiddleware Next, ILog logger):Base(next) {_logger=logger; } Public Override AsyncTask Invoke (Iowincontext context) {_logger. Loginfo ("Middleware begin"); await This. Next.invoke (context); _logger. Loginfo ("Middleware End"); }}
Startup file
Public class startup{ publicvoid Configuration (Iappbuilder app) { app. use <LoggerMiddleware> (new Tracelogger ()); var New httpconfiguration (); // app. Usewebapi (config); // Additional middleware Registrations }}
Here, if you are an MVC developer then please don't look down, now it takes a little time to think about it, what is the meaning of this thing, and what is the difference between the conventional MVC we use? This code runs much faster than running MVC, at least IIS does not start the IIS module loading mechanism, nor does it precompile the page.
I think Owin is a great framework within ASP. He can simplify the many unnecessary modules that are now in MVC. These unnecessary modules are making our programs bloated and bulky. Obviously a little web if you do it with MVC, you'll find that using PHP or directly with ASP. NET PAGES will be much faster than that. It is possible that Owin is a trend in the future of ASP. As a developer we have the right to determine what we want and what we don't, rather than to plug the "powerful" functionality into our projects.
Next we'll look at how the same functionality is done in node. js, and then let's evaluate which is better:
App.js (essential file for express launch)
var express = require (' Express '); var logger = require (' Morgan '); App.use (Logger (' dev ')); App.listen (3001);
Compared to the actual code, there is not much to write about in the app, but it is noteworthy that express is a mature frame, and Owin is a newborn. What you do inside the Owin is a one-off implementation, and express may just go to NPM to find out what good modules to install. Now all the examples of Owin found on the ASP. JS add-on has a well-known out-of-the-box module, just as OAuth is a bitter b feature, there is a lot of content on the ASP to say it, you can try to do in express, it is simply hand to the grab.
SignalR
Say SignalR, about this content began to contact when the solution he really very praise, but see Google in the WebRTC on the technical demonstration after the feel SignalR is a big flicker. SIGNALR is actually just a mechanism for reverse communication via Webstocket (server-side client). Microsoft is called "Real-time communication" between the server and the browser, the content of which is not difficult to implement, but unfortunately Webstocket is being banned by WEBRTC technology, SignalR do a lot of things we can install a very famous module under Nodejs: Socket.io It's done, and Socket.io not only can do real-time communication between server and client, but also can do many functions of instant communication, the function is extremely powerful!
var app = require (' Express ') (); var server = require (' http '). Server (app); var io = require (' Socket.io ') (server); Io.on (function/** / }); Server.listen (3000);
This is one of the simplest communication server code built using Socket.io in Express. Signalr that point of the matter did not want to say, really even explain it also feel very tired. (^_^ I am a very lazy and very fond of simple people). suggestions If you want to start SignalR friends can first see about Socket.io, now Microsoft and the former is not the same, the old Bob will be Ms Play rotten will very simple things are made of no one willing to use the behemoth, even we follow the MS do technology also suffer.
Routing Routing
I prefer the use of epxress in routing, its definition of processing is relatively simple and easy to understand, and he is more likely to get the current running of the routing object, the code to speak:
var express = require (' Express '); var router = Express. Router (); Router.get (function(req, res) { var id= req.params.id; ...}). Post (function(req,res) { // Direct Control post method var Postdata=req.body; ...});
1. The definition of parameters is simpler than using regular expressions in ASP. (Of course, you can also write regular expressions directly)
2. Note req.body This object (need to introduce the Body-parser module first), this is the browser-side post from the form and is already a JSON object, unlike in MVC to do OData to normal processing JSON
3. One side of the definition side coding, which I like. When a project is in the middle of the road, it is easy to find it.
And look back at MVC's definition of router:
The first is RouteConfig.cs (the most annoying thing is that every route needs to have a name!) )
Public classRouteconfig { Public Static voidregisterroutes (routecollection routes) {routes. Ignoreroute ("{Resource}.axd/{*pathinfo}"); Routes. MapRoute (Name:"Default", URL:"{Controller}/{action}/{id}", defaults:New{controller ="Invoice", action ="Index", id =urlparameter.optional}); } }
Then: InvoiceController.cs
Public class Invoicecontroller:controller { public actionresult Index (int ID) { return View (); } }
When there are more than 50 route definitions in my project, I'm looking for the relationship between routing and control .... Bitter b ah ....
View Engine
I basically don't use other view engines in my ASP. NET MVC project because I feel that there is nothing better and faster than razor. I was a little bit confused when I first used node. js, because there are so many view engines that can be supported on express! I think the choice of many developers is not a very real good, because for a small white words to choose who is the best , this is a big problem. After some Google, and finally found it-jade. and Jade as well as: EJS, Coffeekup. In the end, I still feel that Jade's code is the least, the easiest to understand. After one or two hours of reading and experimentation basically learned. From the code volume can be less than razor half, running very high speed. And one of my favorite thing is that he can support dynamic compilation and output. This is going to be done in Razor. A Virtualprovider class can be implemented by embedding the page into assembily, and the process is painful. Here you just want to show two pieces of code, a glimpse of Jade, and a dynamic compilation page. (I'm a little lazy here, not the implementation of ASP. NET MVC, if you are interested you can try it out with ASP. NET MVC, which is the second step)
Look at Jade.
Set a Layout.jade (motherboard) similar to ASP.
DOCTYPE htmlhtml head title= title include./includes/head link (href= "/styles/style.css", rel= " Stylesheet ") Block head body.page block header block content block footer
and get a login.jade.
Extends. /layoutblock content. Row Div (class= "col-lg-4 col-md-8 col-sm-12 col-lg-centered") Form.text-center (style= " padding:20px; ") Div img (src= "/logo.png") P . Input-group span.ctrl-addon i.icon-user-3 input#username ( Type= "text" name= "UserName" required= "required" autofocus= "autofocus" placeholder= "Enter your user account or email") C10/>p label input (type= "checkbox" Name= "RememberMe") span Remember me span.pull-right A Forgot your password? P button (class= "primary fill-width") Login div a.fill-width (role= "button") sign up
Compare razor to know exactly how much code is missing.
Dynamic compilation-Dynamically outputs a Web page content that supports markup format
app.use ("/dynamic-page/", function (req, RES) { var lines=[]; // Let the engine directly format the output of markup Lines.push ( "markup:" * * * Bold * * word "); Lines.push ( "p." ); Lines.push ( "Here is one of the simplest paragraph words" Lines.push ("#{model.name}");
var _fn= jade.compile (lines.join ( )
res.send (_fn ({model:{name: "I am a dynamically compiled context object name"});
There is absolutely no problem in dynamically outputting text within an action in ASP., but it is very painful to pass in a context object and then dynamically compile the output. This feature is very useful in making the mail template, I can only find one in ASP. Razor syntax to support the class library and re-compile the output of this Web page content, this practice is enough to be brain-crippled.
Summary
Good days feel nodejs+express is a word: cool ! And more about the function of Express I did not say here, we go to the official website to see it. If you have a different view or think that Express has a more mysterious function, then leave me a message.
Related resources:
Installation: NPM Install Express
Official website: http://expressjs.com/