[英]Post request works in postman but not in javascript fetch function
[英]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
應作為RequestInit
的body
屬性提供,如下所示:
確保使用正確的
Content-Type
header。 您可以在 MDN 上閱讀有關使用FormData
對象的信息。
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.