02-middleware.js 3.8 KB

// # middleware


var serveFavicon = require('serve-favicon');
var path = require('path');
var winstonRequestLogger = require('winston-request-logger');
var methodOverride = require('method-override');
var bodyParser = require('body-parser');
var responseTime = require('response-time');
const express  = require('express')
// var busboy = require('connect-busboy');


exports = module.exports = function (IoC, logger, settings, policies) {

	var app = this;

	// ignore GET /favicon.ico
	// app.use(serveFavicon(path.join(settings.publicDir, 'favicon.ico')));

	if (settings.server.env === 'development') {

	}

	// static server (always keep this first)
	// <http://goo.gl/j2BEl5>
	app.use('/', express.static('public'));
	// adds X-Response-Time header
	app.use(responseTime({
		digits: 5
	}));

	// prepare req.log for error handler
	app.use(function (req, res, next) {
		req.log = {
			response_time: new Date().getTime(),
			path: req.path,
			query: req.query,
			body: req.body,
			params: req.params
		};
		next();
	});

	app.use((req, res, next) => {//跨域OPTIONS
		if (req.path !== '/' && !req.path.includes('.')) {
			res.set({
				'Access-Control-Allow-Credentials': true, //允许后端发送cookie
				'Access-Control-Allow-Origin': req.headers.origin || '*', //任意域名都可以访问,或者基于我请求头里面的域
				'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type', //设置请求头格式和类型
				'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',//允许支持的请求方式
				'Content-Type': 'application/json; charset=utf-8',//默认与允许的文本格式json和编码格式
			});
		}
		req.method === 'OPTIONS' ? res.status(204).end() : next();
	});

	if (settings.server.env === 'production') {//production 生产环境
		app.use((req, res, next) => {
			//script-src: 	外部脚本
			//style-src:	样式表
			//img-src:		图像
			//media-src:	媒体文件(音频和视频)	
			//font-src:		字体文件
			//object-src:	插件(比如:flash)
			//child-src:	框架
			//frame-ancestor:	嵌入的外部资源(比如:<frame> <iframe> <embed> <appled>)
			//connect-src:		http链接(通过XHR、WebSockets、EventSource等)
			//worker-src:		worker脚本
			//manifest-src:		manifest文件
			let other_origins = [
				'cdn.ronghub.com',
				'at.alicdn.com',
				'gosspublic.alicdn.com',
				'webapi.amap.com',
				's22.cnzz.com',
			];
			const getKeys = () => {

				let str = [], base_str = "'self' " + other_origins.join(' ') + " https: http: filesystem: blob:";
				let obj = {
					'child-src': base_str,
					'connect-src': base_str,
					'font-src': base_str + " data:",
					'frame-src': base_str + " data:",
					'img-src': base_str + " data:",
					'media-src': base_str + " data:",
					'object-src': base_str + " data:",
					'worker-src': base_str + " 'unsafe-inline' 'unsafe-eval'",
					'script-src': base_str + " 'unsafe-inline' 'unsafe-eval'",
					'style-src': base_str + " 'unsafe-inline'",
				}

				for (var key in obj) {
					str.push(key + ' ' + obj[key] + ';');
				}

				return str.join('');

			}

			res.set({
				'Content-Security-Policy': "default-src 'self' https: http:;" + getKeys()
			});
			next();
		});

	}


	// winston request logger before everything else
	// but only if it was enabled in settings
	if (settings.logger.requests) {
		app.use(winstonRequestLogger.create(logger));
	}

	// parse request bodies
	// support _method (PUT in forms etc)
	app.use(
		bodyParser.json({ limit: '50mb' }),
		bodyParser.urlencoded({
			limit: '50mb',
			extended: true
		}),
		methodOverride('_method')
	);
	//support "application/x-www-formurlencoded" or starts with "multipart/*"
	// app.use(busboy({  
	//     limits: {
	//       fileSize: 10 * 1024 * 1024
	//     }
	// })) 

};

exports['@require'] = ['$container', 'igloo/logger', 'igloo/settings', 'policies'];