如何使用 Luvit 进行 POST 请求

我正在为我的一个项目使用Luvit,该项目使用一些在线 API 来使事情更简单。其中一个 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">
...
基本上表示是一个错误请求
</html>
]]

有没有人可以帮助我正确地使用 luvit 进行 REST 操作,特别是 POST?

点赞
用户12918181
用户12918181

你的http.request按预期运作,并返回响应表(response table)(不仅是头部)和**正文字符串(body string)**。

你在发送时使用了Content-Type: application/json, 但发送的数据是无效的。正文(body)必须是有效的 JSON 对象:

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))
      -- 或者是相同的静态字符串[[{"param1": "string1", "data": {"key": "value"}}]]
    print(res.code)
    print(body)
end)()
2020-03-11 10:25:32