For complete separation of front-end systems, development time we need to configure the server to the front, of course, we can choose Nginx like the server configuration, but we can also use NodeJS high degree of freedom to build front-end development server.
simple static server
Here is a simple static server:
var http = require('http'),
url = require('url'),
fs = require('fs')
path = require('path');
function getContentType(_path){
var contentType,
ext = path.extname(_path);
switch(ext){
case '.html':
case '.htm':
contentType = 'text/html';
break;
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.gif':
contentType = 'image/gif';
break;
case '.jpg':
contentType = 'image/jpeg';
break;
case '.png':
contentType = 'image/png';
break;
case '.ico':
contentType = 'image/icon';
break;
default:
contentType = 'application/octet-stream';
}
return contentType;
}
function httpService(req, res){
var reqUrl = req.url,
pathName = url.parse(reqUrl).pathname,
filePath;
if(Path.extname(pathName) === ""){
pathName += "/";
}
if(pathName.charAt(pathName.length - 1) === "/"){
pathName += "index.html";
}
filePath = path.join('./', pathName);
fs.exists(filePath, function(exists){
if(exists){
res.writeHead(200, {'Content-Type': getContentType(filePath)});
var stream = fs.createReadStream(filePath, {flags : "r", encoding : null});
stream.on('error', function(){
res.writeHead(404);
res.end('<h1>404 Read Error</h1>');
});
stream.pipe(res);
}else{
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>404 Not Found</h1>');
}
});
}
var webService = http.createServer(httpService);
webService.on('error', function(error){
console.log('[WebService][error] ' + error);
});
webService.listen(300, function(){
console.log('[WebService][Start] running at http://127.0.0.1:' + 3000 + '/');
});
can be found in a static server also write a lot of lines of code to complete, but if we use connect , will find it all just a few lines of code.
Connect?
connect high-performance NodeJS Web middleware framework that provides more than twenty middleware, and there are many third-party middleware support. connect using very simple, such as the above static server, connect the just:
var connect = require('connect');
var app = connect()
.use(connect.static('public'))
.listen(3000);
installation connect
we just enter the command line:
npm install connect
will be installed.
model
connect the model is very simple, through use registered middleware, middleware receives each request and response, if the request is found to deal with this middleware, then dealt with through response.end output, or to the next through the next a middleware processing.
demand
OK, now we need to see is how:
- is separated from the front-end, so when the front-end development is separated, then the front-end and back-end interaction will make cross-domain, so the first thing to be able to reverse proxy to the backend.
- can simply configure a static server (we assume that the whole front of the file is static).
- can interact with the front-end analog data, which is stored in a specific folder simulated data, and then the corresponding return.
- strive simple configuration via json.
path structure:
/ static: static service path to interact with the backend
/ prototype / static: a prototype interactive data path and analog
/ prototype / static / mockup-data /: analog data path
code
static.js:
module.exports = (function(){
"use strict"
var connect = require('connect'),
http = require('http'),
url = require('url'),
path = require('path'),
proxy = require('proxy-middleware'),
fs = require('fs'),
pkg = JSON.parse(fs.readFileSync('./package.json'));
// 通过后缀名得到content type
function _getType(extname){
switch(extname){
case '.json':
return 'application/json';
case '.xhtml':
case '.html':
return 'text/html';
default:
return 'application/json';
}
}
// 使用connect
var app = connect()
// 使用logger中间件
.use(connect.logger('dev'))
// 用static中间件处理静态服务
.use(pkg.static.path, connect.static(pkg.static.root, {maxAge: pkg.maxAge}))
.use(pkg.prototype.path + '/static/mockup-data', function(req, res, next){
// 如果是GET方法,交由下面的中间件处理
if(req.method === 'GET') return next();
var urlObj = url.parse(pkg.prototype.root + req.originalUrl.replace(pkg.prototype.path, '')),
filePath = urlObj.protocol + urlObj.pathname,
contentType = _getType(path.extname(urlObj.pathname)),
method = req.method.toLowerCase(),
// 得到与方法名对应的模拟文件路径,例如原来文件路径是1.json,在POST方法中变成1.post.json
methodFilePath = filePath.replace(/(\.xhtml|\.html|\.json)$/, '.' + method + '$1');
fs.exists(methodFilePath, function(exist){
// 如果方法名对应的模拟文件存在
if(exist){
// 替换文件路径
filePath = methodFilePath;
}
// 读取文件
fs.readFile(filePath, function(err, data){
if(err) return next(err);
res.writeHead(200, {'Content-Type': contentType});
res.statuCode = 200;
res.end(data);
});
});
})
// 用static中间件处理原型的静态服务
.use(pkg.prototype.path, connect.static(pkg.prototype.root, {maxAge: pkg.maxAge}))
// 使用proxy-middleware中间件进行反向代理
.use(proxy(url.parse(pkg.proxy)))
.listen(pkg.port, function(){console.log('Connect with: http://127.0.0.1:' + pkg.port)});
})();
package.json:
{
"maxAge": 3600,
"port": 80,
"proxy": "http://192.168.10.202:8080",
"prototype": {
"path": "/prototype",
"root": "C:/Users/Desktop/manggis/manggis_web/src/main/webapp/prototype"
},
"static": {
"path": "/manggis_web/static",
"root": "C:/Users/Desktop/manggis/manggis_web/src/main/webapp/static"
},
"devDependencies": {
"connect": "~2.8.4",
"proxy-middleware": "~0.4.0"
}
}
没有评论:
发表评论