2016-09-19 20 views
10

私は(ES2017のasync/awaitと、ここで使用される)新しい取得APIを使用すると、このようなGETリクエスト作ることができることを知っている:Fetch APIを使用したPOSTリクエスト?

async getData() { 
    try { 
     let response = await fetch('https://example.com/api'); 
     let responseJson = await response.json(); 
     console.log(responseJson); 
    } catch(error) { 
     console.error(error); 
    } 
} 

をしかし、どのようにあなたはPOSTリクエストを作るのですか?

+2

あなたがそこに二つの異なるものconflatingしている:[APIのフェッチ]はJavaScriptの次期 'async' /' await'を、そして(完全に独立した)(https://fetch.spec.whatwg.org/)。あなたの質問は、JavaScriptの 'async' /' await'とは何の関係もなく、 'fetch'に関するものです。 (新しいFetch APIはまったく新しいものであり、最新のブラウザに限定されています(http://caniuse.com/#feat=fetch))。 –

+0

@ jfriend00:私はそれをしましたそれら。 –

答えて

23

長い話を短く、また、あなたはよりパーソナルな要求のためのオブジェクトを渡すことができます取得:

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

fetch("http://example.com/api/endpoint/", { 
    method: "post", 
    headers: { 
    'Accept': 'application/json', 
    'Content-Type': 'application/json' 
    }, 

    //make sure to serialize your JSON body 
    body: JSON.stringify({ 
    name: myName, 
    password: myPassword 
    }) 
}) 
.then((response) => { 
    //do something awesome that makes the world a better place 
}); 

は、さらに多くのグッズや落とし穴のドキュメントをフェッチをチェック非同期のtry/catchパターンを実行しているので、私の例ではthen()関数を省略します;

4

JSONとしてデータを送信せずに簡単な投稿要求をしたい場合。

fetch("/url-to-post",{ 
     method: "POST", 
     //what ever data you want to post with key value pair   
     body: "name=manas&age=20", 
     headers: { 
      "Content-Type": "application/x-www-form-urlencoded" 
     }).then((response) => { 
     //do something awesome that makes the world a better place 
}); 
関連する問題