简体   繁体   中英

Vert.x: How to send a post request?

My first Vertx Web app :

public class RequestResponseExample extends AbstractVerticle {

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();

        Router router = Router.router(vertx);

        router.post("/Test").handler(rc -> rc.response().sendFile("index.html"));

        vertx.createHttpServer()
            .requestHandler(router)
            .listen(8080);
    }

}

我认为您发送了一个 get 请求,但是在您的代码中您处理了一个返回 html 文件的 post 请求......我认为首先您必须处理一个返回 html 页面的 get 请求,并为表单编写一个路由。

"

Solution

Change router.post( to router.get( .

Description

Currently, you are configuring the Router to only handle HTTP POST request. That means, it is configured to respond to such an HTTP request:

POST /Test

But when you try to open localhost.8080/Test in your browser, it will send such a request to your server:

GET /Test

This is why you have to tell the router to handle GET and not POST requests.

Additional information: GET and POST are so called HTTP request methods . If you want to learn more about that, I recommend you to read the following article: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

About Verticles

In your code, you can remove extends AbstractVerticle and it will work the same way. If you want your code to get executed in the context of a verticle you have to create an instance of your class and then you have to deploy it:

public class RequestResponseExample extends AbstractVerticle {

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();

        vertx.deployVerticle(new RequestResponseExample());
    }

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

        router.post("/Test").handler(rc -> rc.response().sendFile("index.html"));

        vertx.createHttpServer()
            .requestHandler(router)
            .listen(8080);
    }

}

Since I see a bit of confusion on your side, you may want to also read the following article about Verticles: https://vertx.io/docs/vertx-core/java/#_verticles

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM