【发布时间】:2020-05-09 17:17:58
【问题描述】:
我想在Deno 中使用HTTP POST 编写一个http 客户端。目前在 Deno 中这可能吗?
作为参考,是在 Deno 中进行 http GET 的示例:
const response = await fetch("<URL>");
我查看了 Deno 中的 HTTP module,目前它似乎只专注于服务器端。
【问题讨论】:
标签: http post httpclient deno
我想在Deno 中使用HTTP POST 编写一个http 客户端。目前在 Deno 中这可能吗?
作为参考,是在 Deno 中进行 http GET 的示例:
const response = await fetch("<URL>");
我查看了 Deno 中的 HTTP module,目前它似乎只专注于服务器端。
【问题讨论】:
标签: http post httpclient deno
做一个multipart/form-dataPOST,可以使用FormData对象打包表单post数据。这是通过 HTTP POST 发送表单数据的客户端示例:
// deno run --allow-net http_client_post.ts
const form = new FormData();
form.append("field1", "value1");
form.append("field2", "value2");
const response = await fetch("http://localhost:8080", {
method: "POST",
headers: { "Content-Type": "multipart/form-data" },
body: form
});
console.log(response)
2020 年 7 月 21 日更新:
根据@fuglede 的回答,将JSON 发送到HTTP POST:
const response = await fetch(
url,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ field1: "value1", field2: "value2" })
},
);
【讨论】:
另一个答案对multipart/form-data编码的数据很有用,但值得注意的是,同样的方法也可以用于提交其他编码的数据。例如,要发布 JSON 数据,您可以只使用一个字符串作为 body 参数,最终看起来像下面这样:
const messageContents = "Some message";
const body = JSON.stringify({ message: messageContents });
const response = await fetch(
url,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: body,
},
);
【讨论】: