"MEAN" Technology stack Development Web application

Source: Internet
Author: User
Tags sendfile

"MEAN" Technology stack Development Web application

In the previous article, we talked about how to use angular to build a front-end framework for a project, and the front end abstracts a service layer to send requests back, and the backend returns the corresponding JSON data. In this article, we introduce how to use Express in the NODEJS environment to set up the service side so that it responds to the front-end requests correctly. The examples in this article are based on our learning Project Questionmaker (Https://github.com/Double-Lv/QuestionMaker)

run an express-based Web serverExpress is a Web application development framework that, based on Nodejs, expands many of the features required for web development, making it easy to access and manipulate request and response. Please note that it is not a concept with nginx or Tomcat, it is a development framework, not a server. Running an express-based Web server is very simple, because Express is tied to your package. You first need to install Express with NPM, and then create a new Server.js file under the project root directory, as follows:
var express = require (' Express '); var app = Express (); app.listen; var _rootdir = __dirname;var Protectdir = _rootdir + '/protect/'; App.use (Express.static (_rootdir));//Register Route app.get ('/', function (req, res) {    res.sendfile (_rootdir+ ') /src/index.html ');}); App.use (function (req, res, next) {     res.status (404). SendFile (_rootdir+ '/src/404.html ');}); App.use (function (err, req, res, next) {     console.error (err.stack);     Res.status. Send (' Error ');});
The above code implements these functions, first creating an HTTP server, listening on port 3000. Then App.use (express.static (_rootdir)), this line is the use of the static file services middleware, so that our project JS, CSS and pictures and other static files can be accessed. Next is to register the route, here only one routing rule, that is, "/" (the root directory of the Web site), when matching to this route to the home page file index.html directly to the browser side with the Res.sendfile method. This allows the browser to use http://127.0.0.1:3001 to access the index.html. Other pages of the site can also be returned by configuring similar routes. Express also supports the configuration template engine, which supports Ejs by default, and you can configure other such as handlebars yourself. But in this project, we are using the angular front-end template, so the backend does not need a template, not configured. Our routing mechanism is also fully used by Ng's front-end routing, so configuring only one in Express is enough. At the end there are two blocks of code, the 404 and 500 error captures, respectively. You may wonder why it is written like this? Can you capture 404 and 500 separately from top to bottom? In fact, this is the Express middleware mechanism, in this mechanism, the processing of client requests like a pipeline, all the middleware in series, as long as a certain middleware to return the request, the end of execution, or from top to bottom processing this request. The process of the above code is to match the path by routing rules first, if the route does not match, it is considered to occur 404. 500 error Note one detail, in the parameters of the callback function, the first one will pass in err, which is the wrong object, to mark a 500 error. Understanding Middleware
The core of Express is the middleware mechanism, which enables us to assemble the functions we need flexibly by using various middleware. Middleware is carried out in the pipeline, so-called pipeline is like a pipeline, each to a processing area, the corresponding middleware can process the request and response objects, processing and then sent to the next processing area. If a processing area terminates the request, such as calling the Send method back to the client, the processing is terminated. In most cases, there are ready-made middleware for us to use, such as parsing the request entity with Body-parser, and routing (also a middleware) to properly distribute the request. For example, we add the following code to the Server.js:
App.use (function (req, res, next) {     console.log (' middleware 1 ');     Next ();}); App.use (function (req, res, next) {     console.log (' Middleware 2 ');});

We have added two middleware, the request will be first captured, then processed, output "middleware 1". Then the next () method is executed and the next middleware is entered. There are only two options after a middleware executes, either using next to point to the next middleware or returning the request. If you do nothing, the request will be suspended, that is, the browser will not be returned, has been in the pendding state. For example, the above middleware 2, will cause the request hangs, this should be eliminated.

Routing DesignRunning the server and understanding how the middleware is programmed, we should then provide the API for the front end. such as the front-end post a request to/api/submitquestion to submit a copy of the data, how can we receive the request and processing it, this is the design of the route. The first parameter passed to App.use can be matched to the corresponding request, for example:
App.use ('/api/submitquestion ', function () {})
This allows you to capture just the request to submit the question, which can be handled in the second parameter, such as inserting data into a database. However, it is important to note that the correct use posture for Express routing is not the case. The app.use is used to match the path of the middleware, not the requested path. Because routing is also a kind of middleware, so this kind of usage can also complete the function, but we should still write according to the official standard. What does the standard look like? The code is as follows:
var apirouter = Express. Router (); Apirouter.post ('/submitquestion ', questioncontroller.save); App.use ('/api ', apirouter);
We are using Express. Router This object, it also has use, post, get and other methods to match the request path. Then we use App.use to pass Apirouter as the second parameter. Note that the first parameter of Apirouter.post and App.use. App.use matches the "root path" of the request, so that the request can be divided into different categories, such as all the asynchronous interface we call the API, then this kind of request we should be hanging under "/api". According to this rule, the routing rules for our entire project are as follows:
Register Route App.get ('/', function (req, res) {    res.sendfile (_rootdir+ '/src/index.html ');}); var apirouter = Express. Router (); Apirouter.post ('/getquestion ', questioncontroller.getquestion); Apirouter.post ('/getquestions ', questioncontroller.getquestions); Apirouter.post ('/submitquestion ', questioncontroller.save); ApiRouter.post ('/ Updatequestion ', questioncontroller.update); Apirouter.post ('/removequestion ', questioncontroller.remove); Apirouter.post ('/getpapers ', papercontroller.getpapers); Apirouter.post ('/getpaper ', papercontroller.getpaper); Apirouter.post ('/getpaperquestions ', papercontroller.getpaperquestions); Apirouter.post ('/submitPaper ', Papercontroller.save); Apirouter.post ('/updatepaper ', papercontroller.update); Apirouter.post ('/removePaper ', Papercontroller.remove); App.use ('/api ', apirouter);

In the second argument of router, we pass in a method such as Questioncontroller.save, what is this thing? How does a bit of MVC taste? Yes, we've been able to match the routing, and how does the business logic of the server and the database access organize the code?

Organize your code with "MVC"Using MVC's structure to organize code is of course the golden rule. Express can use the template engine to render the view layer, the routing mechanism to organize the controller layer, but express does not explicitly specify how the MVC structure should be written, but the free choice to you, to organize the MVC structure. Of course you can also organize other forms, such as "N-tier architecture" in Java. In this project, we will simply organize them in the form of folders. Because we used the front-end template, the backend view layer does not exist, only the controller and model. Look at the project directory: Under protect there are two folders controllers and models respectively put C and M. The Questioncontroller object used in our routing is defined in Questioncontroller.js to see how the Save method used to save the question is defined:
var Question = require ('.. /models/question '); module.exports = {     //Add question     save:function (req, res) {          var data = req.body.question;          Question.save (data, function (err, data) {               if (err) {          res.send ({success:false, error:err});     }     else{          res.send ({success:true, data:data});}}          );     }}
Questioncontroller as a module, using the standard COMMONJS syntax, we define the Save method, and through the req.body.question, we can get the data sent by the foreground. In this module, we require the model layer of the question, yes, it is used to manipulate the database, Call the Question.save method, the data is stored in the database, and in the callback function, we use Res.send to return the JSON data to the front end. After defining the Questioncontroller, we can give it to require in the server.js, and then we have the one we used in the route.
Apirouter.post ('/submitquestion ', questioncontroller.save);
The whole process is in collusion. Models folder is the model, used to manage the mapping and interaction with the database, where the use of mongoose as a database operating tools, the model layer how to write, this article does not introduce, in the next article we will explain in detail. Finally, the code of this article is based on a practice project Questionmaker, in order to better understand the narrative in the article, please check the source of the project: Https://github.com/Double-Lv/QuestionMaker classification: JavaScript Related tags: JavaScript, Nodejs, express

"MEAN" Technology stack Development Web application

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.