Unified Big Front (2)--mock.js + node. js How to break up with the back end

Source: Internet
Author: User
Tags generator install node node server

"The big front of the Unified Lake" series is their own front-end learning notes, designed to introduce JavaScript in the non-web development field of application cases and find all kinds of Fun JS library, not regularly updated. If you understand the front-end or write page binding event, then you really are a little out, the front-end can do things already too much,,,,, 手机app开发 桌面应用开发 用于神经网络人工智能的库 页面游戏 数据可视化 and even 嵌入式开发 , what fire on what, berthelot off a rubbing hot little expert . If you also feel that the front-end of the daily development is a bit dull, you might as well look at the front end of another appearance.

Why are you always out of class?

Most engineering projects for the convenience of maintenance, most will use a front-end separation of the development, and the front-end and back-end work is also issued at the same time, the front-end developers will be very embarrassed, the back end in the work, the leader will almost certainly let you do a 静态页面 look at the first, At this time between you and the backend may be just an agreement between the interface (of course, there may be no agreement on the interface, then I can only wish you happiness), and no data transmission, unable to directly get the data to fill the page, if the front-end code is written in place, then the page prompts when opening the page does not get the data, the

The real problem is that 静态页面 it is so fast that your leader will think that when you add the code to the 静态页面 logical part of JavaScript, it should be very fast , In fact, the amount of code in the logical part and the work of the Union is almost 5-10 times that of writing a static page.
Basically the development of a requirement at the front end requires at least a static page ---- business logic + static data --- business logic +http requests and data processing these different forms to completion, So the real timeline becomes this:

role Stage 1 Stage 2 Stage 3 Stage 4 Stage 5 Stage 6
Back end Write Background code Write Background code Go home to sleep Go home to sleep or busy other things Modify the front-end commit bug Repeat 4-5 until you can go online
Front Write a static page No-purpose Change style Write front-end logic Edge development Front side Test interface No-purpose Change style Repeat 4-5 until you can go online

No matter from which aspect, the front end is a handyman, no matter from which angle, the front end is also a little brother face, not the class seems to be.

node. js

When node fires up, the front end is popular like this: not the front end of node. JS, is incomplete, simply put, node. JS extends JavaScript capabilities to a critical step in the service side, and JS has since started its own pervasive manipulation of how to use node. js to set up a local server, and this article uses the Express framework to quickly build mock servers.

Mock.js

Mock.js(GitHub warehouse address) is a generated mock data (that is, virtual data) JS Library, the syntax is simple but very easy to use, support the front end and the service side of the two environmental references, interested readers can click on the link above to learn, the official Wiki provides a full set of documents, up to 1 hours to get started.

Working Style Advantages Disadvantage
Client Easy to operate, pure front-end local can be realized 1. Interface management is not easy 2. A collaborator can't get mock data
Service side 1. Front-end code almost no need to change 2. Access to mock data by other personnel Need to build a mock server, which is slightly more complex than the former

Simply browse through how it's used:

# 安装npm install mockjs// 使用 Mockvar Mock = require('mockjs')var data = Mock.mock({    // 属性 list 的值是一个数组,其中含有 1 到 10 个元素,每个元素均包含id,name,description属性    'list|1-10': [{        'id|+1': 1,// 属性 id 是一个自增数,起始值为 1,每次增 1        'name': '@cname',//占位符语法,生成一个中文名称        'description|3-5':'@csentence',//占位符语法,生成3-5个中文句子        'area':'@province',//省份占位符,将随机生成省份名称    }]})// 输出结果console.log(JSON.stringify(data))
What is the task on the front end?

The essence of front-end development is the data collection and data presentation , that is, the data submitted by the user is sent to the server accurately and securely, the data transmitted by the server is displayed on the interface in accordance with the design diagram, whether or not the interface has been beautified by the CSS, and is optimized for ease of interaction design. The most essential thing is the same.
In other words, what you need to do is that the backend gives the correct data, make sure to show it according to the design, give a hint when the backend gives the data incorrectly, and try not to let the script exit.

Doing things with Nodejs and mockjs.

The recommended approach is to use the node. JS Framework Express to quickly build a server, with the backend staff to set up a good interface, using Mock.js to generate various types of virtual data on the server side, front-end developers directly docking mock servers

What you should do is write the front-end code in place at once and be able to quickly locate the anomaly, and then go home to sleep instead of working aimlessly and waiting to cross the line with others.

1. Install node. js
+ 安装后打开cmd命令行,输入`node -v`, 若正确显示版本号则安装成功。

The attachment contains: nodeV8.9.4 version of the Windows installation package

2. Install other dependent packages
    • yarn(Alternative to NPM's package management tool): npm install yarn (optional)
    • express(Express framework):npm install express -g
    • express-generator(Express Project Generation plugin):npm install express-generator -g
    • mockjs(Analog data Generation Library):npm install mockjs

If the installation is slow, switch NPM source to CNPM or use yarn for package management

3. Generate a new Express project and write the service side

This article seeks to be simple and rough, only the use of non-Express directory structure, interested students can self-study

♬3.1 Open a command line under the specified path, enter express mockserver to generate mockserver a project named

♬3.2 Open the app.js file, add the following code after the var app = Express () to mask the cross-domain:

            app.all('*', function(req, res, next) {                res.header("Access-Control-Allow-Origin", "*");                res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");                next();            });

♬3.3 the users.js format of the file and the way it is routed in the app.js file (any skilled code mover must understand), introduces mockjs , generates the random data needed, and returns the generated data when a request is received from the front-end:

//服务端响应代码片段/routes/operationboard.js://业务逻辑为查询系统告警信息列表//node服务器启动后,请求地址为:127.0.0.1:3000/operationboard/systemwarn//3000端口为express默认启动端口var express = require('express');var router = express.Router();var Mock = require('mockjs');var Random = Mock.Random;router.get('/systemwarn', function (req, res, next) {  var data =Mock.mock({      'list|20':[{            'id|+1':1,            'serial_number|1-100':1,            'warn_number|1-100':1,            'warn_name|1':['流水线编排服务异常','磁盘占用超过阈值'],            'warn_level|1':['紧急','重要'],            'warn_detail':'环境IP:10.114.123.12,服务名称:XX',            'create_time':Random.datetime(),            'finish_time':Random.datetime(),            'contact|4':'abc'        }]       });  res.send({    meta : {      message: 'success'    },    status:true,    data: data.list  })})module.exports = router;

Browser access can play back data on the console:

♬3.4 Open the command line tool in the mockserver project directory, enter npm start , after the service starts, open the front page to see the simulation data returned by the server.

♬3.5 the ability to turn on other people's access is to build a server locally.

Implementation approach via express project to implement node server

Copy the front-end code to the public folder in the Express project directory ( /mockserver/publicin this case), open the command line tool input ipconfig query the native IP, Replace 127.0.0.1 with a native IP, and then access it directly in the browser to open the Web page.

Implementation Mode 2--traditional Apache server

For ease of management, direct use of the open source XAMPP integration environment, the installation of the completion of a button to open the Apache server, and copy the front-end code to the installation directory in the Htdoc folder in subfolders, and then in a similar way in 1 in the browser access, because the server code to remove the cross-domain restrictions, Therefore, even if the port number is different, the Apache server site can still access the node server interface and get the data.

♬3.6 Finally, the project is what we do together, not you get rid of the responsibility of the finished, for everything you do to provide a reference to visit excel文档 and send it to work with you to develop the back end is polite practice.

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.