node系列之代理中间件和https服务器

node小技巧

  • 本文遇到的问题是因为想把公司的项目从一个较旧的脚手架react-redux-starter-kit迁移到react-boilerplate

一、node服务器想使用proxy

  • 前端项目的node服务器如果没有使用webpack-dev-server,但是又想使用proxy功能;于是大致扫了一下webpack-dev-server的源码,发现其使用了http-proxy-middleware这个中间件
1.安装http-proxy-middleware
1
yarn add http-proxy-middleware
2. 示例用法
1
2
3
4
5
6
7
8
9
10
const app = express()

const filter = (pathname) => pathname.match('^/cloud');

const apiProxy = proxy(filter, {
target: 'https://www.baidu.com', //你的代理目标url
secure: false,
});

app.use(apiProxy);
  • 详细用法参考该库的github仓库

二、如何搭建https服务

  • 原项目使用node server的是https协议,而react-boilerplate使用的是http
1. 生成证书
1
2
3
4
5
openssl genrsa -out privatekey.pem 1024

openssl req -new -key privatekey.pem -out certrequest.csr

openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem
2. 建立https服务器
1
2
3
4
5
6
7
8
9
const fs=requires('fs');
const https=requires('https');
const app=express();
const options = {
key: fs.readFileSync(path.join(__dirname, './privatekey.pem')),
cert: fs.readFileSync(path.join(__dirname, './certificate.pem')),
};
const httpsServer = https.createServer(options, app);
httpsServer.listen(8002);

三、http请求首部如何加入Authorization