Angular 2 + Vert.x:HTTP请求的收发主体

时间:2018-07-14 13:22:04

标签: java angular typescript http-post vert.x

我使用Vert.x框架服务器端和Angular 2(v6.0.9)客户端创建了一个简单的REST应用程序。我要做的是使服务器显示接收到的数据。但是,我无法弄清楚如何检索HTTP请求正文:routingContext.getBodyAsString()routingContext.getBodyAsJson()都返回null。作为一个临时解决方案,我设法使用getParam("data")方法通过path参数显示了所有已发送的数据。我在做什么错了?

服务器代码

package test.post;

import java.util.HashSet;
import java.util.Set;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.json.Json;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.CorsHandler;
import io.vertx.ext.web.handler.StaticHandler;

public class Server extends AbstractVerticle {

    @Override
    public void start() throws Exception {
        Router router = Router.router(vertx);

        Set<String> allowedHeaders = new HashSet<>();
        allowedHeaders.add("x-requested-with");
        allowedHeaders.add("Access-Control-Allow-Origin");
        allowedHeaders.add("origin");
        allowedHeaders.add("Content-Type");
        allowedHeaders.add("accept");
        allowedHeaders.add("X-PINGARUNER");

        Set<HttpMethod> allowedMethods = new HashSet<>();
        allowedMethods.add(HttpMethod.GET);
        allowedMethods.add(HttpMethod.POST);
        allowedMethods.add(HttpMethod.OPTIONS);
        allowedMethods.add(HttpMethod.DELETE);
        allowedMethods.add(HttpMethod.PATCH);
        allowedMethods.add(HttpMethod.PUT);

        router.route().handler(CorsHandler.create("*").allowedHeaders(allowedHeaders).allowedMethods(allowedMethods));

        router.post("/test/post/handler/:data").handler(this::receive);

        // Serve the static pages
        router.route().handler(StaticHandler.create());

        vertx.createHttpServer().requestHandler(router::accept).listen(8080);
        System.out.println("Service running");
    }

    private void receive(RoutingContext routingContext) {
        System.out.println("received post request");
        System.out.println(routingContext.getBodyAsString());
        System.out.println(routingContext.getBodyAsJson());
        System.out.println(routingContext.request().getParam("data"));
        routingContext.response().putHeader("Content-Type", "application/json").end(Json.encodePrettily("ok"));
    }

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        Server service = new Server();
        vertx.deployVerticle(service);
    }
}

客户端app.component.ts代码

import { Component } from '@angular/core';
import { RequestService } from './request.service';

@Component({
  selector: 'app-root',
  template: `
    <h2>Click to send post request</h2>
    <button type="submit" (click)=makePostRequest()>Send Post Request</button>
    `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private requestService: RequestService) { }

  makePostRequest() {
    this.requestService.sendRequest().subscribe(response => console.log(response));
  }
}

客户request.service.ts代码

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { catchError, tap } from 'rxjs/operators';
import { Observable, of } from 'rxjs';

export class User {
  email: string;
  password: string;
  address: string;
  username: string;
}

@Injectable({
  providedIn: 'root'
})
export class RequestService {

  constructor(private http: HttpClient) { }

  sendRequest(): Observable<any> {
    let user = new User();
    user.username = 'Admin';
    user.email = 'admin@gmail.com';
    user.password = 'admin';
    user.address = 'somewhere';

    console.log(user);

    let url = 'http://127.0.0.1:8080/test/post/handler/' + JSON.stringify(user);
    let headers = new HttpHeaders({ 'Content-Type': 'application/json' });
    let options: { headers, responseType: 'json' };
    return this.http.post(url, JSON.stringify(user), options).pipe(
      tap(response => console.log(response))
    );
  }
}

1 个答案:

答案 0 :(得分:2)

您需要启用正文处理程序才能读取请求正文,例如:

router.route("/test/post*").handler(BodyHandler.create());
router.post("/test/post/handler/:data").handler(this::receive);

或全局启用它:

router.route().handler(BodyHandler.create())