-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
56 lines (49 loc) · 1.47 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// 本地开发server 能力
const path = require('path');
import webpack from 'webpack'; // es6 import
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import config from './webpack-dev-config';
// express server
const app = new(require('express'))();
const port = 3000; // 监听的端口是3000 locahost:3000
const compiler = webpack(config);
//这个库来实现反向代理
const httpProxy = require('http-proxy')
//设置静态资源根目录
app.use(new(require('express')).static('static'));
// dev中间件
app.use(webpackDevMiddleware(compiler, {
noInfo: true, // 不显示编译信息
publicPath: config.output.publicPath,
stats: {
colors: true
}
}));
app.use(webpackHotMiddleware(compiler));
//设置代理
var proxy = httpProxy.createProxyServer({
target: 'https://m.news.baidu.com',
changeOrigin: true,
});
app.all('/news', function(req, res) {
proxy.web(req, res);
});
// 捕获异常
proxy.on('error', function(err, req, res) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Something went wrong. And we are reporting a custom error message.');
});
//返回静态数据
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(port, function(error) {
if (error) {
console.error(error)
} else {
console.info("==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port)
}
});