代码之家  ›  专栏  ›  技术社区  ›  Giacomo Venturini

角度2+vert.x:发送HTTP请求的接收主体

  •  0
  • Giacomo Venturini  · 技术社区  · 8 年前

    我使用Vert.x框架服务器端和Angular2(V6.0.9)客户端制作了一个简单的REST应用程序。我要做的是让服务器显示接收到的数据。但是,我不知道如何检索HTTP请求主体:两者都是 routingContext.getBodyAsString() routingContext.getBodyAsJson() 返回空值。作为临时解决方案,我设法通过路径参数显示所有发送的数据,使用 getParam("data") 方法。我做错什么了?

    服务器代码

    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));
      }
    }
    

    客户端请求.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 回复  |  直到 8 年前
        1
  •  2
  •   ledniov    8 年前

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

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

    或全局启用:

    router.route().handler(BodyHandler.create())
    
    推荐文章