postdvibed

vibed: How can I handle POST request?


Could anybody help me to handle POST request, I read docs, but it's not clear to me, how to handle POST request, that I send from page, to vibed server.

I wrote next code:

import vibe.d;
import std.stdio;

void main()
{

    auto router = new URLRouter;
    router.any("*", &accControl);
    router.any("/my", &action);

    auto settings = new HTTPServerSettings;
    settings.port = 8080;
    settings.bindAddresses = ["::", "127.0.0.1"];

    listenHTTP(settings, router);
    runEventLoop();
}

void accControl(HTTPServerRequest req, HTTPServerResponse res)
{
    res.headers["Access-Control-Allow-Origin"] = "*";
}


void action(HTTPServerRequest req, HTTPServerResponse res)
{
    // how get string from POST request here. And how get JSON object, if server send it.
}

but what method I should use for req? As I understand expect POST body there is sending a lot of other data.

The POST request is sending with JQuery:

$.post("http://127.0.0.1:8080", "\"answers_result\":777");

So I need to get this JSON and send with vibed it's to DB. But problem that I can't understand how to handle it.


Solution

  • In main:

    auto router = new URLRouter;
    router.post("/url_to_match", &action);
    
    listenHTTP(settings, router);
    

    Action:

    void action(HTTPServerRequest req, HTTPServerResponse res)
    {
        auto answers_result = req.json["answers_result"].to!int;
    
        // ...
    }
    

    Or you can use registerRestInterface.