Some questions about the separation of front and back ends of Node.js?

  node.js, question

Recently, the company plans to optimize the WEB side of an old project, and plans to use Nodejs as the front end, so as to share most of the interfaces with APPlication and reduce the maintenance workload of the back end.

I am a little white, and have always been interested in the front end, so I am responsible for the development of this project.
I did some homework before, so I finally decided to choose express for nodejs framework. If the template is more like ejs, UIkit will directly bootstrap and jquery.

The first question is to know how the directory structure should be defined. I designed it according to express’s default directory structure. I would like to know what kind of directory structure is more professional or reasonable. Next, I will talk about my directory structure and the contents and composition of the documents. Please give me some advice.

clipboard.png

  • Bin is generated by express by default.

  • Config contains some configuration files and some common methods, which will be introduced one by one below.

  • The logs log directory is mainly composed of the access log, the request URL of the request server and the return result log.

  • Other this useless, release some of my own temporary writing, production environment inside does not have this

  • Node_modules This is not explained (I think some said that this can be removed, but there is no attempt yet)

  • Public static file directory, if this directory, the production environment will be placed under the nginx directory

  • Routes route, my route is a service to establish a route

  • Views template, similar to routing, a business establishes a folder and corresponding template files

Each file is described in detail below.

  • 1.config directory

clipboard.png

  • Dz_msg.js contains some returned tips

clipboard.png

  • Js contains some common methods.

clipboard.png

  • Reslogs is the configuration of log4j.

clipboard.png

  • Settings are some configuration information.

clipboard.png

  • 2.logs directory contains the user’s access log, the request URL of the request back-end server structure and the record of the returned results, which are convenient for viewing and analysis and optimization in the future.

clipboard.png

  • 3.routes directory

clipboard.png

  • 4.views directory

clipboard.png

The above is my catalogue and file composition. I hope experts can help me to give advice. I am a small white one, and see how my project can be improved and better. Thank you

The second question is, my APP.JS also asked experts to see if the writing is reasonable and what middleware or security considerations are needed for an internet product.

var express = require('express');
 var fs = require('fs');
 var path = require('path');
 var favicon = require('serve-favicon');
 var logger = require('morgan');
 var cookieParser = require('cookie-parser');
 var session = require('express-session');
 var bodyParser = require('body-parser');
 var filestream = require('file-stream-rotator')
 
 //Load configuration file
 var settings = require('./config/settings');
 //Load routing file
 var index = require('./routes/index');
 var search = require('./routes/search');
 var users = require('./routes/users');
 var business = require('./routes/business');
 var maps = require('./routes/maps');
 var direct = require('./routes/direct');
 var tourism = require('./routes/tourism');
 
 var app = express();
 
 //Set the template file type, directory and suffix of Express
 app.set('views', path.join(__dirname, 'views'));
 app.engine('.html', require('ejs').__express);
 app.set('view engine', 'html');
 
 //Set up development environment and log
 var logdir = path.join(__dirname, 'logs');
 fs.existsSync(logdir) || fs.mkdirSync(logdir);
 var alogstream = filestream.getStream({
 date_format: 'YYYYMMDD',
 Filename: path.join (logdir,' access-percentage DATE percentage.log'),
 frequency: 'daily',
 verbose: false
 })
 app.use(logger('combined', {stream: alogstream}));
 //Load and parse json middleware
 app.use(bodyParser.json());
 //Load and Resolve urlencode Middleware
 app.use(bodyParser.urlencoded({ extended: false }));
 //Load and parse cookie middleware
 app.use(cookieParser());
 //Load Static File Directory Settings
 app.use(express.static(path.join(__dirname, 'public')));
 //set session
 app.use(session({
 //String used to encrypt session data. This attribute value is a required attribute.
 secret: settings.SESSION_SECRET,
 //indicates the name of the cookie, and the name of the default cookie is: connect.sid
 //name: 'bjbus.com',
 //cookie expiration time, ms.
 //cookie: {maxAge: 60000},
 //Refers to resetting the session cookie for each request. Assuming that your cookie expires in 6000 milliseconds, you will set another 6000 milliseconds for each request.
 resave: true,
 //refers to resetting the session cookie every time a request is made, assuming that your cookie expires in 6000 milliseconds, and every request will be reset in 6000 milliseconds.
 saveUninitialized: true,
 }));
 
 app.use(function(req, res, next){
 res.locals.title = settings.SITETITLE;
 res.locals.keywords = settings.SITEKEYWORDS;
 res.locals.description = settings.SITEDISCRIPTION;
 var _user = req.session.userinfo;
 if(_user){
 res.locals.userinfo = _user;
 bracket
 next();
 });
 
 //Set Route Pointing
 app.use('/', index);
 app.use('/search', search);
 app.use('/users', users);
 app.use('/business', business);
 app.use('/direct', direct);
 app.use('/maps', maps);
 app.use('/direct', direct);
 app.use('/tourism', tourism);
 
 
 module.exports = app;

The third problem is that I don’t know how to write more succinctly on the page judgment of the session after the user logs in. The following is my current writing method, but this is the place where every session needs to be judged, and I feel a little tired.

clipboard.png

The fourth problem is that I realized this when logging in. After the user enters the login page, my husband forms a uuid. I use IP plus random number plus SESSION_SECRET and then Message-Digest Algorithm 5 it out. Then I put this value into the session. When the user logs in, he needs to submit the user name, password and uuid. The server verifies whether the uuid is consistent with the session. If the same proves no problem, then it judges whether the user information is correct. The following is the code

  • Landing page

/* Login Page */
 router.get('/login', function(req, res, next) {
 if(req.session.userinfo){
 res.render('error.html', {
 errormsg: msg.is_login
 });
 return;
 bracket
 
 Varuuid = functions.getclientip (req) plus functions.randomNum(false, 6) plus settings.SESSION_SECRET;
 uuid = functions.dz_md5(uuid);
 req.session.uuid = uuid;
 Res.locals.title = "user login-"plus res.locales.title;
 res.render('login.html', {
 uuid: uuid
 });
 
 });
  • Login processing page

/* login processing */
 router.post('/doLogin/:u/:p/:uuid/:r', function(req, res, next) {
 if(req.session.userinfo){
 res.json({
 errormsg: msg.is_login
 });
 return;
 bracket
 var u = req.params.u
 ,p = req.params.p
 ,uuid = req.params.uuid;
 if(uuid == req.session.uuid){
 if(functions.isEmpty(u) || functions.isEmpty(p)){
 res.json({errorMsg: msg.user_error});
 }else{
 var param = [];
 param.push("v_act=v_login")
 Param.push("v_mid= "plus settings.Interface.mid");
 Param.push("v_pass= "plus p");
 Param.push("v_uname= "plus u");
 functions.dz_http_get(param, function(data){
 if(typeof data === 'string'){
 res.json({errorMsg: data});
 }else{
 var userinfo = {
 uid: data.uid,
 uname: data.uname,
 phone: data.phone
 bracket
 req.session.userinfo = userinfo;
 req.session.uuid = null;
 res.json(data);
 bracket
 });
 bracket
 
 }else{
 res.json({errorMsg: msg.login_overtime});
 bracket
 });

At present, it is just the beginning, and there may be many further problems. Please help us a lot! If there are any problems, they will continue to be updated, please!

Continue to update the problems encountered-0718

First, let’s see how my http.get is written.

dz_http_get: function(param, callback){
        //param 是接口需要的参数
        param = param.join("&");
        param 加= "&v_sign=" 加 this.dz_md5(param加settings.Interface.key);
        var url = settings.Interface.url 加 param;
        logger.info(url);
        http.get(url, function(response) {
            if(response.statusCode == 200){
                var resJson = "";
                response.setEncoding('utf8');
                response.on('data', function(data){
                    resJson 加= data;
                });
                response.on('end', function () {
                    logger.debug(resJson);
                    resJson = JSON.parse(resJson);
                    if(resJson.v_status == "00"){
                        return callback(resJson.v_data)
                    }else{
                        return callback(resJson.v_scontent)
                    }
                });
            }else{
                return callback(msg.response_err)
            }
        }).on('error', function(e) {
            return callback(msg.request_err)
        });
},

At present, I have encountered such a problem. If the URL I submit to the server interface contains Chinese, the http.get of node.js returns 400 errors. If the Chinese encode is ok, links containing Chinese are ok in the browser, but the error is reported in node. please also ask the great god to see what the problem is.

http://xxxxxx?v_act=v_ecpeople&v_mid=10005&v_pic=10007510000000000001&v_pid=46272&v_pname=百分比E9百分比98百分比BF百分比E6百分比96百分比AF百分比E9百分比A1百分比BF&v_ptel=13800000001&v_tel=13671378601&v_type=1&v_uid=1&v_sign=a69bc72211cb8da82dc02467742fb80a

http://xxxxxx?v_act=v_ecpeople&v_mid=10005&v_pic=10007510000000000001&v_pid=46272&v_pname=阿斯顿&v_ptel=13800000001&v_tel=13671378601&v_type=1&v_uid=1&v_sign=a69bc72211cb8da82dc02467742fb80a

It’s like this …
What nodejs do here should be considered as the middle end. After all, the front-end usually refers to your views in express inside, nodejs and express. It is more appropriate to calculate the back-end, except that people’s nodejs and express usually access databases while you access another set of api.

One thing can be reminded: you have to spend an hour thinking about the connect mechanism in express, that is, what exactly is the middleware mechanism. Middleware is designed to help you deal with situations where a large api requires the same pre-or post-operations.

We directly use the api written by nodejs to operate the database, and the front end uses SPA, which goes further than your way. However, we started from 0, which is more convenient for such design. We have to analyze the specific situation.