0

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.

Max Alibaev
  • 681
  • 7
  • 17
Dmitry Bubnenkov
  • 9,415
  • 19
  • 85
  • 145
  • FYI `std.stdio.writeln` is part of blocking I/O. You should not use it inside event loop. – sibnick Nov 25 '15 at 12:01
  • I should point out that `"\"answers_result\":777"` is invalid JSON. You probably meant `"{\"answers_result\":777}"`. – sigod Nov 25 '15 at 12:06
  • 1
    JS tip: use single quotation mark. E.g. `'{"answers_result": 777}'` — see? There's no need to escape `"`. – sigod Nov 25 '15 at 12:08
  • @sigrod, thanks for tip! But what in Chrome console I see string with quoter marks before first and after last element of answer? (--> `"{"QID ... `) and `90}"` `["{"QID": 1, "AID": 5, "SubAID":[],"MinArea": 10, "MaxArea": 90}"]` When I creating JSON string I do not have them: `var answers_string = (`{"QID": question.id, "AID": _answer.id, "SubAID":[SubAID_val],`).replace("question.id", question.id).replace("_answer.id", _answer.id); ` – Dmitry Bubnenkov Nov 25 '15 at 12:34
  • Why not just `JSON.stringify({ QID: question.id, AID: _answer.id, ... })`? – sigod Nov 25 '15 at 12:53
  • Thanks, I will try it now! – Dmitry Bubnenkov Nov 25 '15 at 12:55
  • About Chrome console: it's just how console represents a string. – sigod Nov 25 '15 at 12:55

2 Answers2

0

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.

Max Alibaev
  • 681
  • 7
  • 17
sigod
  • 3,514
  • 2
  • 21
  • 44
  • Could you show what function should be in `action() {}`, I do not understand how to extract request. – Dmitry Bubnenkov Nov 25 '15 at 11:59
  • Thans, but why I see in Log of Chrome `POST http://127.0.0.1:8080/my 404 (Not Found)` I thought if server start I should see status `200` – Dmitry Bubnenkov Nov 25 '15 at 12:07
  • @user1432751 Did you configured your router? E.g. `router.post("/my", &action);` – sigod Nov 25 '15 at 12:11
  • 1
    I updated my example in start topic to my present code. In example you are specified name if incoming data, but what if I do not know this name? Could you also show how to handle simple text, not json – Dmitry Bubnenkov Nov 25 '15 at 12:28
  • @user1432751 You can use [`Json`](http://vibed.org/api/vibe.data.json/Json) API to full extend, I've just provided usage example. – sigod Nov 25 '15 at 12:50
  • @user1432751 Then you need to use [`HTTPServerRequest.bodyReader`](http://vibed.org/api/vibe.http.server/HTTPServerRequest.bodyReader), but read documentation carefully. – sigod Nov 25 '15 at 12:51
  • thanks I will try to understand docs, but I can't understand why I am getting `404` error. And I would be very pleased if you will explain what should I do if I do not name of element that is coming to server. In your example it's named "answers_result" --> `req.json["answers_result"].to!int;` – Dmitry Bubnenkov Nov 25 '15 at 14:17
0

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

Ma'moon Al-Akash
  • 4,445
  • 1
  • 20
  • 16