【问题标题】:Post Request with forms (and JavaScript fetch())使用表单(和 JavaScript fetch())发布请求
【发布时间】:2022-01-27 00:37:51
【问题描述】:

如何在帖子 (JavaScript fetch()) 请求中发送表单参数? 例如 curl --form "avatar=@me.jpg" "https://example.com/api/v4/endpoint"

我尝试了以下代码:

const form = new FormData()
form.append("foo":"bar")
fetch( "https://someapi.org/api", {
    method: 'POST',
    headers:form
} )
    .then( response => response.json() )
    .then( response => {
        console.log(response)
    } );
}

这对我不起作用。

【问题讨论】:

  • 您可能想在body 中使用FormData 实例而不是headers
  • @Phillip 我已经尝试过了,但是在我使用的 api 的 Node-API 中,我使用的是在 Deno/Web 中不存在的 form.getHeaders() 的标头中

标签: javascript typescript http fetch deno


【解决方案1】:

FormData 应作为RequestInitbody 属性提供,如下所示:

确保使用正确的 Content-Type 标头。您可以在 MDN 上阅读有关 Using FormData Objects 的信息。

TS Playground

so-70865955.ts:

async function example () {
  const form = new FormData();
  form.append("foo", "bar");

  const apiAddress = "https://someapi.org/api";

  const init: RequestInit = {
    method: 'POST',
    headers: new Headers([['content-type', 'application/x-www-form-urlencoded']]),
    body: form,
  };

  const response = await fetch(apiAddress, init);
  const data = await response.json();
  console.log(data);
}

// Invoke it
example();

在您的控制台中:

deno run --allow-net so-70865955.ts

【讨论】:

猜你喜欢
  • 2017-01-26
  • 1970-01-01
  • 2020-11-11
  • 2010-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多