该实例为moleculer集成express、moleculer-web、expres文件上传中间件multer试下文件上传功能
代码如下:
"use strict";
const ApiGateway = require("moleculer-web");
const fs = require('fs');
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
var moment = require('moment');
var multer = require('multer');
module.exports = {
name: "api",
mixins: [ApiGateway],
settings: {
port: process.env.PORT || 4000,
//关闭moleculer开发http服务功能
server: false,
//打开moleculer-web中间件功能
middleware: true,
routes: [
{
aliases: {
'POST file/upload'(req, res) {
res.end('aaa');
}
}
}
],
//设置跨域
cors: {
// Configures the Access-Control-Allow-Origin CORS header.
origin: ["*"],
// Configures the Access-Control-Allow-Methods CORS header.
methods: ["GET", "OPTIONS", "POST", "PUT", "DELETE"],
// Configures the Access-Control-Allow-Headers CORS header.
allowedHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Content-Length', 'Authorization'],
// Configures the Access-Control-Expose-Headers CORS header.
exposedHeaders: [],
// Configures the Access-Control-Allow-Credentials CORS header.
credentials: true,
// Configures the Access-Control-Max-Age CORS header.
maxAge: 3600
},
},
created() {
//创建express实例
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// var upload = multer({ dest: path.join(__dirname, './uploads') });
//设置文件上传中间件
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname, './uploads'))
},
filename: function (req, file, cb) {
var date = new Date();
cb(null, moment().format('YYYY-MM-DD') + '_' + file.originalname);
}
});
var upload = multer({ storage: storage });
app.use(upload.any());
//使用moleculer-web作为中间件
app.use('/', this.express());
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
this.app = app;
},
started() {
//express监听端口
this.app.listen(this.settings.port, err => {
if (err) {
return this.broker.fatal(err);
}
console.log('server started');
})
},
stopped() {
//服务停止是关闭express
if (this.app.listening) {
this.app.close(err => {
if (err) {
console.log(err);
}
console.log('server stopped');
})
}
}
};
网友评论