gpt4 book ai didi

java - Angular 2 + 垂直 x : send-receive body of HTTP requests

转载 作者:行者123 更新时间:2023-12-02 02:02:43 25 4
gpt4 key购买 nike

我使用 Vert.x 框架服务器端和 Angular 2 (v6.0.9) 客户端制作了一个简单的 REST 应用程序。我想做的是让服务器显示接收到的数据。但是我不知道如何检索 HTTP 请求正文:routingContext.getBodyAsString()routingContext.getBodyAsJson() 都返回 null。作为临时解决方案,我设法使用 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));
}
}

客户端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))
);
}
}

最佳答案

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

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

或全局启用它:

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

关于java - Angular 2 + 垂直 x : send-receive body of HTTP requests,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51339915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com