简体   繁体   English

Http 客户端在 Deno 中使用 HTTP POST

[英]Http Client using HTTP POST in Deno

I would like to write a http client in Deno using an HTTP POST .我想使用HTTP POSTDeno中编写 http 客户端。 Is this possible in Deno at this time?目前在 Deno 中这可能吗?

For reference, is an example of doing an http GET in Deno:作为参考,是在 Deno 中执行 http GET 的示例:

const response = await fetch("<URL>");

I looked at the HTTP module in Deno and it appears to be focused on server side only at this time.我查看了 Deno 中的HTTP 模块,此时它似乎只专注于服务器端。

To do a multipart/form-data POST , form post data can be packaged using the FormData object.要进行multipart/form-data POST ,可以使用FormData object 打包表单发布数据。 Here is a client side example for sending form data over HTTP 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)

Update 2020-07-21: 2020 年 7 月 21 日更新:

As per answer from @fuglede, to send JSON over HTTP POST :根据@fuglede 的回答,通过HTTP POST发送JSON

    const response = await fetch(
      url,
      {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ field1: "value1", field2: "value2" })
      },
    );

The other answer is useful for multipart/form-data -encoded data, but it's worth noting that the same approach can be used to submit data of other encodings as well.另一个答案对于multipart/form-data编码的数据很有用,但值得注意的是,同样的方法也可以用于提交其他编码的数据。 For instance, to POST JSON data, you can just use a string for the body argument, which ends up looking something like the below:例如,要发布 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,
  },
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM