2016-08-05 4 views
1

https://developer.mozilla.org/en-US/docs/Web/API/Requestに従ってください。次のスニペットは、JavaScriptでPOST Requestインスタンスを作成できます。JavaScriptでPOSTリクエストインスタンスを作成できません

var myRequest = new Request('http://localhost/api', {method: 'POST', body: '{"foo":"bar"}'}); 

var myURL = myRequest.url; // http://localhost/api 
var myMethod = myRequest.method; // POST 
var myCred = myRequest.credentials; // omit 
var bodyUsed = myRequest.bodyUsed; // true 

しかし、私のChromeブラウザでは、私は身体なしでインスタンスを得たが、実際に私はRequestに身体にオプションを渡します。 enter image description here

どうすればPOSTリクエストを作成できますか?

答えて

1

リクエストはまだ実験中ですので、XMLHttpRequestと一緒にPOSTリクエストを行います。

var http = new XMLHttpRequest(); 
var url = "get_data.php"; 
var params = "lorem=ipsum&name=binny"; 
http.open("POST", url, true); 

//Send the proper header information along with the request 
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 

http.onreadystatechange = function() {//Call a function when the state changes. 
    if(http.readyState == 4 && http.status == 200) { 
     alert(http.responseText); 
    } 
} 
http.send(params); 
1

おそらくすべてがMDN Requestに記載されているわけではありません。私はOPサンプルを再現しましたが、次の段落のコードを追加すると結果が異なります。

function doReq() { 
     var myRequest = new Request('json.php', { method: 'POST', body: '{"foo":"bar"}' }); 

     console.log(myRequest); 
     //return; //when uncommented returns bodyUsed: false 
     //when commented bodyUsed: true and body goes to the server 
     console.log(JSON.stringify(myRequest)); //{} all the time 
     fetch(myRequest) 
.then(function(response) { 
    if(response.status == 200) return response.json(); 
    else throw new Error('Something went wrong on api server!'); 
}) 
.then(function(response) { 
    console.debug(response); 
    // ... 
}) 
     .catch(function(error) { 
      console.error(error); 
     }); 
    } 

テストケース:
FF 47.0.1 - 上記のように。
Googleのクロム51から
エッジ上記のように - '要求が' https://developer.mozilla.org/en-US/docs/Web/API/Requestによれば、(予想通り)

1

未定義です。リクエストにbodyプロパティはありません。だからあなたはクロームのコンソールログでそれを見ることはできません。

あなたのリクエストにはbodyプロパティがあり、実際に使用することができます。リクエストを取得すると、実際にボディが取得されます。ここに私のテスト結果があります。

その他のご質問がある場合は、コメントを残してください。

関連する問題