Frames

Untitled

0
1
1const createError = require('http-errors');
2const express = require('express');
3const path = require('path');
4const compression = require('compression');
5const cookieParser = require('cookie-parser');
6const logger = require('morgan');
7const multer = require('multer');
8
9const indexRouter = require('./routes/index');
10
11const app = express();
12const storage = multer.diskStorage({
13 destination(req, file, cb) {
14 cb(null, './upload/');
15 },
16 filename(req, file, cb) {
17 cb(null, file.originalname);
18 }
19});
20const upload = multer({ storage });
21
22// view engine setup
23app.set('views', path.join(__dirname, 'views'));
24app.set('view engine', 'pug');
25
26// 尽量在其他中间件前使用compression
27app.use(compression());
28app.use(logger('dev'));
29app.use(express.json());
30app.use(express.urlencoded({ extended: false }));
31app.use(cookieParser());
32app.use(express.static(path.join(__dirname, 'public')));
33app.use('/upload', express.static(path.join(__dirname, 'upload')));
34
35app.use('/', indexRouter);
36app.use((req, res, next) => {
37 res.set({
38 'Access-Control-Allow-Origin': '*',
39 'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, OPTIONS',
40 'Access-Control-Allow-Headers':
41 'Content-Type, Authorization, Content-Length, X-Requested-With'
42 });
43
44 // intercepts OPTIONS method
45 if (req.method === 'OPTIONS') {
46 // respond with 200
47 res.send(200);
48 } else {
49 // move on
50 next();
51 }
52});
53// 单图上传
54app.post('/upload', upload.single('file'), (req, res, next) => {
55 const { file } = req;
56 res.send({
57 code: 'Success',
58 data: [file],
59 status: true
60 });
61});
62
63// 多图上传
64app.post('/uploads', upload.array('file'), (req, res, next) => {
65 const { files } = req;
66 res.send({
67 code: 'Success',
68 data: files,
69 status: true
70 });
71});
72
73// catch 404 and forward to error handler
74app.use((req, res, next) => {
75 next(createError(404));
76});
77
78// error handler
79app.use((err, req, res, next) => {
80 // set locals, only providing error in development
81 res.locals.message = err.message;
82 res.locals.error = req.app.get('env') === 'development' ? err : {};
83
84 // render the error page
85 res.status(err.status || 500);
86 res.render('error');
87});
88
89module.exports = app;
90