当前位置:网站首页>[notes on the practice of node middle tier (I)] -- building the project framework

[notes on the practice of node middle tier (I)] -- building the project framework

2022-07-23 09:56:00 Lily

Preface :
     This article is about learning Node Notes on the practice of the middle tier , It is recommended that you can read Keyon Y The original text of the big man Node Middle tier practice . Before starting this article , You can also read the following first ,Node Middle tier practice ( One )—— be based on NodeJS Full plank development , It is helpful to understand the content of this article .(PS: Continue to pay debts node The small white ╮(╯▽╰)╭)

One 、 The scaffold ?

     Every time we start a new project , May need to be based on project needs , Build a new scaffold , According to the selected front-end frame , To install official recommendations . such as , Use angular2,vue2 Classmate , The official recommended installation method is , Through dedicated angular-cli、vue-cli To quickly build a webpack compile 、 Packaged project framework .
     that , Inspired by tools , At the beginning of the project , We can also develop one based on webpack Project framework for :

  • Use express carrying webpack-dev-middleware and webpack-hot-middleware Conduct Thermal loading ;
  • built-in dev( development environment ) and production( Production environment ) Two kinds of Starting mode .

Two 、 Technology selection

2.1 node Development framework

express and koa A choice .

  • express Closer to Web Framework The concept of ;
  • express The function is very simple , It is completely composed of routing and middleware web Development framework : essentially , One Express Applications are just calling various middleware ;
  • koa Use co As the underlying running framework , Using it completely forgets when to call back functions or callbackshell;
  • express The history is longer , Large installed capacity , Well documented , There are also many third-party middleware ;
    this , choice express As node Development framework .

2.2 template engine

Direct selection pug As a server-side template engine .pug It is a relatively flexible server-side template ,express It's easy to configure , At the root app.js Configuration in file .

// Set the type of template engine app.set(‘view engine’,‘pug’); // Set the template file path app.set(‘views’,path.resolve(_dirname,‘src/Views’));

   such , stay express Use... When rendering res.render(‘Home/index’,{}), Specify the corresponding page template path , The second parameter is to be in pug The data content used by the page ,json Format .

2.3 Asynchronous communication between the middle layer and the back end

   Actually , That's it. ajax library , therefore , I chose axios,vue2 Officially recommended ajax library , Built in axios.all(), You can proxy multiple back-end requests in the middle tier and return them together , Make it easy Bigpipe.

2.4 modularization

   Because it is the front page of the website , You need to consider SEO, Cannot use the front-end frame , So change your mind , Use webpack+es6/AMD To achieve modularity . therefore , Use webpack As a packer +View Modularity of layer , from The front-end level realizes modularization and componentization .es6 Use in Contorl Modularity of layer , stay node The middle layer realizes modularization .

3、 ... and 、 Environment configuration ( Startup file )

  app.js As the startup file of the project , yes express Configuration file for , It is also a running development environment / Configuration files for the production environment .
   Through documents node Command parameters configured at startup , from app.js Receiving parameters , Then run the corresponding environment
   We need to install cross-env This plugin

npm i --save-dev cross-env

   stay package.json Of script Middle configuration :

"scripts": {
    
    "start": "cross-env NODE_ENV=production node app.js",
    "dev": "cross-env NODE_ENV=dev supervisor -w app.js app",
    "build": "webpack --config build/webpack.prod.config.js"
}

   such , Use process.env.NODE_ENV You can get it node Starting environment parameters .
   here , Configured the development environment (dev) And the production environment (production)

  • development environment : Don't compress code , Turn on devtool Generate source-map, Easy to debug code ;
  • Production environment : Yes, it is webpack package 、 Compress 、 Confusion operation , Will eventually complete the code ( application ) Output to dist Directory , And then it starts node The server , Run the application ;
    The above code also uses supervisor plug-in unit , This is listening node The configuration file (app.js) Change of , And restart automatically node Of .
npm i --save-dev supervisor

The front-end level uses webpack-dev-middleware and webpack-hot-middleware, Realize hot loading .
such , Hot loading is realized from the middle layer to the front end .

3.1 node Middle layer configuration

In the root directory , New config Folder , Some commonly used configurations / Parameters 、 Methods extract , It's written in config/config.js and config/common.js in .
for example , M-server startup port number 、 Root of application (path.resolve(_dirname,‘…/’))、 Back end server ip、 front end SEO Of description and keywords Equal parameter , It's all there config.js in , adopt AMD The specification is uniformly introduced in all documents used , Easy to modify .
app.js

var express = require('express');
var cookieParser = require('cookie-parser');
var path = require('path');
var localOptions = require('./build/localOptions');
var config = require('./config/config');
var bodyParser = require('body-parser');
var auth = require('./middleware/auth');
var log4js = require('./config/log4js');

process.env.NODE_ENV = process.env.NODE_ENV ? process.env.NODE_ENV : 'production';
var isDev = process.env.NODE_ENV === 'dev';
var app = express();
var port = config.port;


app.set('view engine', 'pug');
//  Set the template file path 
if (isDev){
    
	app.set('views', path.resolve(__dirname, 'src/Views'));
}else {
    
	app.set('views', path.resolve(__dirname, 'dist/Views'));
}

// app.locals The defined key value pairs can be accessed directly in the template 
app.locals.env = process.env.NODE_ENV || 'dev';
app.locals.reload = true;

app.use(cookieParser());
app.use(bodyParser.urlencoded({
    extended: false}));


if (isDev) {
    
    // app.locals.pretty = true;
	//  development environment , Static files use hot plug 
	var webpack = require('webpack');
	var webpackDevMiddleware = require('webpack-dev-middleware');
	var webpackHotMiddleware = require('webpack-hot-middleware');
	var webpackDevConfig = require('./build/webpack.dev.config.js');

	var compiler = webpack(webpackDevConfig);
	//  Hot plug 
	app.use(webpackDevMiddleware(compiler, {
    
		publicPath: webpackDevConfig.output.publicPath,
		noInfo: true,
		stats: 'errors-only'
	}))
	app.use(webpackHotMiddleware(compiler, {
    
		heartbeat: 1000,
		noInfo: true,
	}));

	//  It cannot be hot swapped down 
	var reload = require('reload');
	var http = require('http');
	var server = http.createServer(app);
	// reload(server, app);
	reload(app);
	server.listen(port, () => {
    
		console.log('App【dev】 is now running on port ' + port + '!');
	});

	//  Static directory settings must have , Read by the development environment vendor.js Not a memory file ;
    //  Static directory settings must be placed in reload Back , Avoid page introduction reload.js Report errors 
    app.use(express.static(path.join(config.root, 'src')));
    app.use('/', require(path.join(config.configRoot,'/routes')));
	
}else {
    
	//  Online environment does not need monitoring , Just turn it on node The service can be 
	//  Set up node Static file directory for 
	app.use(express.static(path.join(config.root, 'dist')));
    app.use('/',require(path.join(config.configRoot,'/routes')));
    // app.listen(process.env.PORT, () => {
    
    app.listen(port, () => {
    
		console.log('App【production】 is now running on port ' + port + '!');
    })
}

//  capture  404 error   Pass to  error route 
app.use('*', auth, (req, res, next) => {
    
	let err = new Error('Not Found');
	err.status = 404;
	next(err);
});

//  Capture  error, Jump to error page 
app.use((err, req, res, next) => {
    
	const sc = err.status || 500;
	if(err.status == 405){
    
		res.redirect(config.cndesignOrigin + '/Home/GuideAuthentication');
		return;
	}
	res.status(sc);
	//  Write the log here 
	log4js.error('\r\n Status: '+ sc + "\r\n Message: " + err.message + "\r\n Href: " + localOptions.baseUrl + req.originalUrl + "\r\n User-agent: " + req.headers['user-agent']);

	res.render('Error/404', {
    
		error: err,
		status: sc,
		message: err.message,
		userInfo: req.userInfo_ || {
     hasLogin: false }
	});
});

Be careful Error Handle The order of mounting , Generally mount to app.use() Next , And to the end .
because Error Handle The parameters for 4 individual , The first parameter err Through next(err) Throw out , In this way, all routes can be thrown at any time error, Give Way Error Handle To capture .
Take a look at the directory structure :

App
├─ .babelrc                         // babel Configuration of 
├─ ReadMe                           
├─ app.js                           //  Startup file 
├─ build                            // webpack Configuration file for 
│    ├─ entrys.js                   // webpack pack js and css Entry file 
│    ├─ localOptions.js             //  Front end developer local configuration file , Local ip Wait for site configuration 
│    ├─ postcss.config.js           // postcss Configuration file for 
│    ├─ webpack.dev.config.js       //  Development environment webpack Packaging configuration 
│    ├─ webpack.dll.config.js       // webpack.DllReferencePlugin Plug in configuration file 
│    └─ webpack.prod.config.js      //  Production environment webpack Packaging configuration 
├─ config                           // Model Layer file : Include node Server configuration 、 Routing and proxy interfaces 
│    ├─ common.js                   //  Common method of middle layer logic processing 
│    ├─ config.js                   // node Server configuration 
│    └─ routes                      //  Routing and proxy interface configuration 
│           ├─ default.js
│           ├─ designers.js
│           ├─ home.js
│           └─ index.js             //  Entry file for routing and interface configuration 
├─ package.json
└─ src                              // View Layer file 
       ├─ Components                //  Common components 
       │    ├─ base
       │    ├─ home
       │    ├─ index
       │    ├─ message
       │    ├─ modals
       │    ├─ page
       ├─ Views                     //  page 
       │    ├─ Default
       │    ├─ Error
       │    ├─ Home
       │    ├─ Include
       │    ├─ Messages
       │    └─ Shared
       └─ assets                    //  Static file directory 
              ├─ Jcrop
              ├─ es5-shim-master
              ├─ images
              ├─ jquery-1.10.2.min.js
              ├─ jquery-ui-1.8.24.min.js
              └─ layui

Reference blog :

Node Middle tier practice ( Two )—— Build the project framework https://juejin.cn/post/6844904191605866510

原网站

版权声明
本文为[Lily]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207230222108596.html