首页 > 解决方案 > 来自客户端的表单数据未到达服务器

问题描述

我正在对 Vert.x Web 服务器执行 POST 操作。我很难将 POST 数据发送到服务器。

我正在使用 Angular 客户端执行 POST。客户端代码如下:

addUser(theCaller: Observer, nwUser: UserInfo): void {
    const thedata: FormData = new FormData();
    const data = JSON.stringify(nwUser);
    thedata.append('uInfo', data);

    const result: Observable<WebResult> = this.httpReq.post<WebResult>('http://localhost:8084/manage/add', thedata);
    result.subscribe({
      next: res => {
        if (res.goodOp === true) {
           console.info('User '+res.userName + 'created.');
        } 
      },
      error: err => {
        console.error('Add operation failed. ' + err);
      }
    });
  }

用于处理 POST 请求的 vert.x 服务器代码如下:

 theRouter.post(path).handler(actx->{
    HttpServerResponse resp = rCtx.response();
    resp.putHeader("content-type",ctxType);
    resp.setChunked(true);
    MultiMap map = theCtx.request().params();

     String str = map.get("uInfo");

     ...do other stuff with str...
 });

问题发生在服务器上。当从 MultiMap 映射中设置 str 时,它始终为 null。事实上,应该包含参数的整个 MultiMap 对象包含许多空值。出于某种原因,我从客户端发送的表单数据没有到达服务器。

我显然错过了一些东西,但我看不到它是什么。我是在客户端做错了什么,还是我在服务器上遗漏了什么?

有人可以对此提供一些见解吗?如何让服务器正确处理表单?

编辑:在发布这个问题之前,我确实尝试使用 Vert.x 获取我的 POST 请求的主体,以便获取我发送的参数。查看 Vert.x 文档和我在 Internet 上其他地方找到的一些随机示例,我想我必须直接从正文中获取 JSON。执行此操作的 Vert.x 代码如下:

theRouter.route().handler(BodyHandler.create());

theRouter.post(path).handler(actx->{
    HttpServerResponse resp = rCtx.response();
    resp.putHeader("content-type",ctxType);
    resp.setChunked(true);

    JsonObject json = actx.getBodyAsJson();
    logger.info("json object contains: "+json);

     ...do other stuff with json...
 });

名为 json 的 JsonObject 也是 null。我的参数似乎仍然没有到达 POST 路线。

标签: angularhttpvert.x

解决方案


推荐阅读