使用 http-proxy-middleware 时,表单参数不会传递给 express 应用程序

Form parameters are not passed to the express app while using http-proxy-middleware

这是一个非常具体的问题,可能很难描述/理解。 我不知道,你需要多少输入,所以我将首先描述我的整个架构: 我目前正在编写我的第一个微服务架构,我正在使用 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;
                }
            })
        );  

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

我正在使用 Insomnia REST 客户端来测试系统。 我有一个身份验证服务,用于对用户进行身份验证。我可以通过正文参数

传递 post 请求 "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>

当我post表单时,auth服务收到了请求,但是请求正文是空的。 为什么在使用网站时请求正文是空的,而在使用 REST 客户端时它可以正常工作?

我看到参数正在从前端传递。

解决方案:

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

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

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

我使用 coexist-parser-proxy (https://github.com/stuartZhang/coexist-parser-proxy (also proposed here: https://github.com/chimurai/http-proxy-middleware/issues/320#issuecomment-570889127))

解决了这个问题