如何使用http-proxy-middleware授权转发网页

时间:2019-04-28 20:20:46

标签: javascript node.js express fetch http-proxy-middleware

我想向我的前端应用程序的用户显示他们自己的网页,该网页在NodeJS Express服务器后面的VPN网络中本地提供服务。

我使用http-proxy-middleware授予对http://192.168.0.17:4000/index.htm网页的访问权限。该页面使用3个.js脚本,因此我不得不将这三个脚本添加到代理目标中:

require("rootpath")();
const express = require("express");
const app = express();
const cors = require("cors");
const bodyParser = require("body-parser");
const jwt = require("_helpers/jwt");
const errorHandler = require("_helpers/error-handler");
var proxy = require("http-proxy-middleware");

var apiProxy = proxy({
  target: "http://192.168.14.111",
  changeOrigin: true,
  logLevel: "debug" 
});

app.use(cors());

app.use(
  [
    "/index.htm",
    "/project.js",
    "/webmicfg.js",
    "/webmi.js"
  ],
  apiProxy
);

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(jwt());

app.use("/users", require("./users/users.controller"));
app.use("/heatpumps", require("./heatpumps/heatpump.controller"));

app.use(errorHandler);

const port =
  process.env.NODE_ENV === "production" ? process.env.PORT || 80 : 4000;
const server = app.listen(port, function() {
  console.log("Server listening on port " + port);
});

用户具有iframe或对象或嵌入代码以访问其网页:

<iframe
  width="600"
  height="400"
  title="sdf"
  src="http://192.168.0.17:4000/index.htm"
/>
<object
  data="http://192.168.0.17:4000/index.htm"
  width="600"
  height="400"
/>
<embed
  src="http://192.168.0.17:4000/index.htm"
  width="600"
  height="400"
/>

但是该访问不受限制。现在任何人都可以指向http://192.168.0.17:4000/index.htm并访问http://192.168.14.111/index.htm

我认为我可以通过获取请求来发送身份验证标头,但获取的html无法正确加载。我尝试过:

<script>
      var headers = new Headers();

      var requestOptions = {
        method: "GET",
        headers: { "Content-Type": "text/html" },
        mode: "cors",
        cache: "default"
      };

      fetch("http://localhost:4000/index.htm", requestOptions)
        .then(function(response) {
          return response.text();
        })
        .then(function(text) {
          console.log(text);
          document.querySelector("#output-frame-id").srcdoc= text;
        });
</script>


<iframe src="" width="600px" height="400px" id="output-frame-id"></iframe>

在控制台中,我得到了html页面,但由于未加载这三个.js脚本而出现未捕获的参考错误,因此未将其加载到iframe中。我认为这不是执行此操作的好方法,因为html页面在与远程服务器不同的上下文中加载。

当您要通过这种方式访问​​转发的网页时,如何向代理发送授权:

<iframe title="sdf" src="http://192.168.0.17:4000/index.htm"/>

0 个答案:

没有答案