React教程(四) : ExpressJS
ExpressJS常用中间件:
npm install cookie-parser --save
npm install body-parser --save
npm install compression --save
npm install errorhandler --save
npm install morgan --save
npm install winston --save
1:cookie-parser
const cookieParser = require('cookie-parser');
app.use(cookieParser());
之后可以在req对象中访问cookies
2:body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
3: compression
对request/reponse做数据压缩
const compression = require('compression');
app.use(
compression({
filter: function(req, res) {
return /gzip/i.test(req.headers['accept-encoding']) && compression.filter(req, res);
}
})
);
4:morgan & winston
记录日志
5: 实例 - 使用expressjs作为react前端项目的host
使用expressjs来承载react前端项目可以带来很多好处,比如同构,实现SSR。 这里先简单介绍一下如何实现
5.1 最简单的实现方式,根目录下新建server文件夹,新建index.js,代码如下:
const path = require('path');
const express = require('express');
const uiAppStatic = path.resolve(__dirname, '../build');
const cookieParser = require('cookie-parser');
require('dotenv').config({ path: path.resolve(__dirname, '../.env.server') });
const PORT = process.env.PORT || 3006;
const app = express();
app.use(cookieParser());
app.get('/', (req, resp) => {
resp.sendFile('index.html', { root: uiAppStatic });
});
app.use(express.static(uiAppStatic));
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
先npm run build, 再运行node server/index.js就可以启动项目。 但这种方式有个问题,如果访问根目录,如:http://localhost:3006/ 一切ok
但如果我直接在浏览器里输入子目录,再回车,就会出现:
这是因为:app.get('/', (req, resp) 这行代码只接受对根目录的访问。 如果改成 app.get('/*', (req, resp) 呢? (加星号作为通配符)
答案是:也不行。 这么做会导致所有的请求都返回index.html, 不论是对css、js、png文件的请求,都返回index.html。
要解决上述问题,必须这么做:
5.2 server文件夹下新建index.js,代码如下:
const path = require('path');
const cookieParser = require('cookie-parser');
require('dotenv').config({ path: path.resolve(__dirname, '../.env.server') });
const PORT = process.env.PORT || 3006;
const app = require('./app');
app.use(cookieParser());
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
5.3 新建app.js,代码如下:
const path = require('path');
const express = require('express');
const appRouter = require('./router');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
require('dotenv').config({ path: path.resolve(__dirname, '../.env.server') });
const uiAppStatic = path.resolve(__dirname, '../build');
const app = express();
app.use(express.static(uiAppStatic));
app.use(cookieParser());
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
app.use('/', appRouter);
module.exports = app;
5.4 新建router.js,代码如下:
'use strict';
const express = require('express');
const v8 = require('v8');
const appRouter = new express.Router();
const path = require('path');
const uiAppStatic = path.resolve(__dirname, '../build');
appRouter.get('/*', (req, resp) => {
resp.sendFile('index.html', { root: uiAppStatic });
});
module.exports = appRouter;
现在运行node server/index.js 就可以解决上述问题。