Node http-proxy-middleware 代理转发
我的代码:
var express = require('express');
var path = require('path');
//var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//var proxy = require('http-proxy-middleware');
const { createProxyMiddleware } = require('http-proxy-middleware');
var app = express();
//这段代码必须放在404 error handler配置之前否则先返回404,无法代理转发
//module.exports = function (app) {
app.use(
"/api",
createProxyMiddleware(
{
target: "http://192.168.95.152:8765",//目标服务器
changeOrigin: true,
//ws: true, // 代理websocket
pathRewrite: {
"/api": ""
}/*,
router: {
// 当请求localhost:3000/api时,会转发到http://localhost:8080,
'localhost:5000/api': 'http://localhost:8765'
}*/
}
)
);
//};
// uncomment after placing your favicon in /public
// app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use('/', express.static(path.resolve(__dirname, '../html')));
app.use('/', express.static(path.resolve(__dirname, '../')));
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
module.exports = app;
静态html页面中的ajax请求:
省略html内容,直接展示js
<!-- Page JS -->
<script>
window.App.run();
$.get("http://localhost:5000/api/restful/ipUtil/getIpAdress?ip=115.115.115.115",function(text){
alert(text);
})
</script>
重要的事情说三遍:
代理配置必须放在404 error handler配置之前否则先返回404,无法代理转发。
代理配置必须放在404 error handler配置之前否则先返回404,无法代理转发。
代理配置必须放在404 error handler配置之前否则先返回404,无法代理转发。