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.


  • 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


  • Dz_msg.js contains some returned tips


  • Js contains some common methods.


  • Reslogs is the configuration of log4j.


  • Settings are some configuration information.


  • 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.


  • 3.routes directory


  • 4.views directory


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
 //Load and Resolve urlencode Middleware
 app.use(bodyParser.urlencoded({ extended: false }));
 //Load and parse cookie middleware
 //Load Static File Directory Settings
 app.use(express.static(path.join(__dirname, 'public')));
 //set 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: '',
 //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;
 res.locals.userinfo = _user;
 //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.


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) {
 res.render('error.html', {
 errormsg: msg.is_login
 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 */'/doLogin/:u/:p/:uuid/:r', function(req, res, next) {
 errormsg: msg.is_login
 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});
 var param = [];
 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});
 var userinfo = {
 uid: data.uid,
 uname: data.uname,
 req.session.userinfo = userinfo;
 req.session.uuid = null;
 res.json({errorMsg: msg.login_overtime});

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;;
        http.get(url, function(response) {
            if(response.statusCode == 200){
                var resJson = "";
                response.on('data', function(data){
                    resJson 加= data;
                response.on('end', function () {
                    resJson = JSON.parse(resJson);
                    if(resJson.v_status == "00"){
                        return callback(resJson.v_data)
                        return callback(resJson.v_scontent)
                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.



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.