node express 中间件 http-proxy-middleware 和 express-http-proxy 转发 搞定 post 超时

2018-11-14

总结: http-proxy-middleware 转发 post 请求 有问题,没找到问题所在,换 express-http-proxy 代理。

前后端独立开发,静态文件、模板等 前端express服务提供。
后端负责接口。
前端开发 转发 ajax 到 测试服务器或者开发服务器。

首先 http-proxy-middleware 中间件转发:

server.js

 1 const express = require('express');
 2 const timeout = require('connect-timeout');
 3 const proxy = require('http-proxy-middleware');
 4 
 5 const app = express();
 6 // 这里从环境变量读取配置,方便命令行启动
 7 // HOST 指目标地址
 8 // PORT 服务端口
 9 const { HOST = 'http://10.10.65.43:8081', PORT = '9090' } = process.env;
10 
11 // 超时时间
12 const TIME_OUT = 3000 * 1e3;
13 
14 // 设置端口
15 app.set('port', PORT);
16 
17 
18 设置超时 返回超时响应
19 app.use(timeout(TIME_OUT));
20 app.use((req, res, next) => {
21   if (!req.timedout) next();
22 });
23 
24 // 静态页面
25 // 这里一般设置你的静态资源路径
26 app.use('/', express.static('static'));
27 
28 // 反向代理(这里把需要进行反代的路径配置到这里即可)
29 let opts = {
30    target: HOST , 
31    changeOrigin: true,
32 }
33 app.use(proxy('/api', opts));
34 app.use(proxy('/fmcp/api', opts));
35 app.use(proxy('/bill-template/api', opts));
36 app.use(proxy('/metadata-service', opts));
37 
38 
39 // 监听端口
40 app.listen(app.get('port'), () => {
41   console.log(`server running @${app.get('port')}`);
42 });

这个http-proxy-middleware 转发get请求没问题,测试post接口的时候503超时,想着是post数据的问题解析的问题,于是引入了body-parser,也没搞定,不知道什么原因。

换了 express-http-proxy 代理试了下。用法上有些不同。

const express = require('express');
const timeout = require('connect-timeout');
// 换代理中间件
const proxy = require('express-http-proxy');

const app = express();
// 这里从环境变量读取配置,方便命令行启动
// HOST 指目标地址
// PORT 服务端口
const { HOST = 'http://10.10.65.43:8081', PORT = '9090' } = process.env;

// 超时时间
const TIME_OUT = 3000 * 1e3;

// 设置端口
app.set('port', PORT);


// 设置超时 返回超时响应
// app.use(timeout(TIME_OUT));
app.use((req, res, next) => {
  if (!req.timedout) next();
});

// 静态页面
// 这里一般设置你的静态资源路径
app.use('/', express.static('static'));

// 反向代理(这里把需要进行反代的路径配置到这里即可)
let opts = {
  preserveHostHdr: true,
  reqAsBuffer: true,
//转发之前触发该方法
  proxyReqPathResolver: function(req, res) {
    //这个代理会把匹配到的url(下面的 ‘/api’等)去掉,转发过去直接404,这里手动加回来,
    req.url = req.baseUrl+req.url;
    console.log(1,req)
    return require('url').parse(req.url).path;
  },

}
app.use('/api', proxy(HOST,opts));
app.use('/fmcp/api', proxy(HOST,opts));
app.use('/bill-template/api', proxy(HOST,opts));

// 监听端口
app.listen(app.get('port'), () => {
  console.log(`server running @${app.get('port')}`);
});

这个 get post 都没问题。

总结: http-proxy-middleware 转发 post 请求 有问题,没找到问题所在,换 express-http-proxy 代理。

猜你喜欢

转载自www.cnblogs.com/websjs/p/9959816.html
今日推荐