任何人都可以帮我处理POST请求,我看了docs,但我不清楚如何处理我从页面发送到振动服务器的POST请求。
我写了下一段代码:
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.
}
但是我应该用什么方法来获取?据我所知,期望POST正在发送大量其他数据。
POST请求正在使用JQuery发送:
$.post("http://127.0.0.1:8080", "\"answers_result\":777");
所以我需要获得这个JSON并将其发送给DB。但问题是我无法理解如何处理它。
答案 0 :(得分:0)
主要:
auto router = new URLRouter;
router.post("/url_to_match", &action);
listenHTTP(settings, router);
动作:
void action(HTTPServerRequest req, HTTPServerResponse res)
{
auto answers_result = req.json["answers_result"].to!int;
// ...
}
或者您可以使用registerRestInterface
。
答案 1 :(得分:0)
这是一个示例代码,用于说明如何从vibe.d读取POST参数:
主要功能:
shared static this()
{
auto router = new URLRouter;
router.post("/url_to_match", &action);
auto settings = new HTTPServerSettings;
settings.port = 3000;
listenHTTP(settings, router);
}
动作:
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);
}
构建程序并运行它,在本地计算机上试用它,您可以执行以下简单的curl请求:
curl --data "first_name=kareem&last_name=smith" "http://localhost:3000/url_to_match"
HTH