簡體   English   中英

使用 forms(和 JavaScript fetch())發布請求

[英]Post Request with forms (and JavaScript fetch())

如何在帖子 (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)
    } );
}

這對我不起作用。

FormData應作為RequestInitbody屬性提供,如下所示:

確保使用正確的Content-Type header。 您可以在 MDN 上閱讀有關使用FormData對象的信息。

TS游樂場

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM