Dmitry Bubnenkov
Dmitry Bubnenkov

Reputation: 9859

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.

Upvotes: 0

Views: 857

Answers (2)

Ma'moon Al-Akash
Ma'moon Al-Akash

Reputation: 5393

Here is an example code to show how to read POST params from vibe.d:

Main Function:

shared static this()
{
   auto router = new URLRouter;
   router.post("/url_to_match", &action);

   auto settings = new HTTPServerSettings;
   settings.port = 3000;
   listenHTTP(settings, router);
}

Action:

void action(HTTPServerRequest req, HTTPServerResponse res)
{
    // Read first POST parameter named "first_name"
    auto firstName = req.form["first_name"];

    // Read second POST parameter named "last_name"
    auto lastName = req.form["last_name"];

    // Prepare output to be sent to client.
    auto name = "Hello %s, %s".format(lastName, firstName);

    // Send data back to client
    res.writeBody(name);
}

Build the program and run it, to try it out on your local machine you may execute the following simple curl request:

curl --data "first_name=kareem&last_name=smith" "http://localhost:3000/url_to_match"

HTH

Upvotes: 0

sigod
sigod

Reputation: 6407

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.

Upvotes: 0

Related Questions