【问题标题】:Form parameters are not passed to the express app while using http-proxy-middleware使用 http-proxy-middleware 时,表单参数不会传递给 express 应用程序
【发布时间】:2020-06-05 20:45:27
【问题描述】:

这是一个非常具体的问题,可能很难描述/理解。 我不知道你需要多少输入,所以我将首先描述我的整个架构: 我目前正在编写我的第一个微服务架构,我使用 nodejs、express 框架、ui 和 http-proxy-middleware 的把手来创建网络。

每个服务都从一个随机端口开始。然后服务在 api-gateway 注册。 api-gateway 将“/api/web/[service]/[rest]”之类的 url 路由到“localhost:[serviceport]/[rest]”(这意味着 webapi-gateway 将 /[rest] 请求路由到服务在注册的服务端口上”。 为了在普通端口 80 上运行整个前端,我创建了一个代理,它将所有以“/api”开头的请求路由到之前定义的网关。对于这两个重定向,我都使用 http-proxy-middleware:

this.app.use(rewritePath,
            this.proxy({
                target: "http://localhost:" + port,
                changeOrigin: true,
                pathRewrite: (path, req) => {
                    console.log(path);
                    var split = path.split("/");
                    split = split.splice(2, split.length);
                    split = split.join("/");
                    if (!split.startsWith("/")) {
                        split = "/" + split;
                    }
                    console.log(path + " to -> localhost:" + port + split);

                    return split;
                }
            })
        );  

我不需要该代码上的 cmets,它只是为了更好地理解。总而言之:它有效。

我正在使用 Insomnia REST 客户端来测试系统。 我有一个身份验证服务,用于对用户进行身份验证。我可以使用正文参数传递发布请求“localhost/api/web/auth/login”

{
    "username":"user",
    "password":"test"
}

我收到了 200 响应,表明它有效。

现在我的问题是: 我创建了一个显示表单的前端:

<form action="/api/web/auth/login" method="post">
   <input name="username" type="text" placeholder="Username" required>
   <input name="password" type="password" placeholder="Password" required>
   <input type="submit" value="Log in">
</form>

当我发布表单时,身份验证服务收到请求,但请求正文为空。 为什么使用网站时请求正文为空,而我使用 REST 客户端时它可以工作?

【问题讨论】:

    标签: html node.js express http-proxy-middleware


    【解决方案1】:

    我看到参数是从前端传递过来的。

    【讨论】:

      【解决方案2】:

      解决方案:

      在其余客户端中,我使用了 json 编码数据,而表单提交了 formdata 编码数据。我添加了

      this.app.use(bodyParser.urlencoded({ extended: true }));
      

      应用程序的中间件。在那之后,我遇到了 http-proxy-middleware 和 bodyParser 不能很好地协同工作,如此处所述: https://github.com/chimurai/http-proxy-middleware/issues/320.

      我使用共存解析器代理解决了这个问题(https://github.com/stuartZhang/coexist-parser-proxy(这里也建议:https://github.com/chimurai/http-proxy-middleware/issues/320#issuecomment-570889127))

      【讨论】:

        猜你喜欢
        • 2019-07-15
        • 2017-03-05
        • 1970-01-01
        • 2020-12-22
        • 1970-01-01
        • 2019-06-14
        • 2022-07-13
        • 1970-01-01
        • 2021-03-31
        相关资源
        最近更新 更多