如何使用 Luvit 执行 POST 请求

How to do a POST request using Luvit

我在我的一个项目中使用 Luvit,该项目使用一些在线 APIs 来简化事情。其中一个 API 要求我向他们的端点发出 POST 请求以处理数据。我查看了他们的官方文档,甚至还查看了一些非官方文档,但最终一无所获。我什至尝试了以下一些方法,但似乎没有任何效果

local http = require("coro-http")

coroutine.wrap(function()
    local head, body = http.request("POST", JSON_STORE_CLIENT, {{"Content-Type", "application/json"}}, "test")
    print(head)
    print(body)
end)()
--[[
table: 0x7f5f4a732148
<!DOCTYPE html>
<html lang="en">
...
basically tells its a bad request
</html>
]]

有人可以帮助我正确地使用 luvit 进行 REST 操作,尤其是 POST 吗?

您的 http.request 按预期工作,它 returns 响应 table(不仅 headers)和 body 字符串.

您发帖 Content-Type: application/json 但发送的数据无效。 Body 必须有效 JSON object:

local http = require("coro-http")
local json = require("json")

coroutine.wrap(function()
    local data = {param1 = "string1", data = {key = "value"}}
    local res, body = http.request("POST", JSON_STORE_CLIENT,
      {{"Content-Type", "application/json"}},
      json.stringify(data))
      -- or static string [[{"param1": "string1", "data": {"key": "value"}}]]
    print(res.code)
    print(body)
end)()