2016-07-30 141 views
0

我花了很多小時試圖解決這個問題,我自己也找不到解決方案。XML HTTP請求Jodel

這是我的jodelclient對象內的一個函數。

this.sendPost = function(JodelPost) 
{ 
    var httpRequest = new XMLHttpRequest(); //create new httpRequest 
    httpRequest.onreadystatechange = function (data) //This is the function that gets called when you recieve the server response 
    { 
     console.log(data); //Prints out the server response 
    } 

    var url = 'https://api.go-tellm.com/api/v2/posts/?'; //BaseUrl for jodel api 

    httpRequest.open('POST', url+JSON.stringify(JodelPost)); 
    httpRequest.setRequestHeader('Authorization', 'Bearer ' + this.token); //For a valid authirazation 
    httpRequest.send(); //send it flying! 
}; 

來自服務器的響應是

「POST https://api.go-tellm.com/api/v2/posts/ 400(錯誤請求)?」

「缺少必需的屬性:位置」

這是對JodelPost變量進行字符串化的結果示例。

{ 
    "color": "FFBA00", 
    "location": { 
     "city": "Uppsala", 
     "country": "46", 
     "loc_accuracy": 0, 
     "loc_coordinates": { 
       "lat": "68.805532", 
       "lng": "2.943903" 
      }, 
     "name": "Uppsala" 
    }, 
    "message": "HelloWorld" 
} 

當我試圖解決這個我自己,我發現這個github上庫做同樣的事情,但在Python。這可能是一些有用的信息。

Pydel

提前感謝!我很新這個簡單的解釋讚賞。

回答

0

在我看來,請求沒有正確創建。您嘗試使用URL發送數據,但它應該在XHR對象的send函數中傳遞。

另外,每當狀態發生變化時都會調用onreadystatechange函數,但當狀態達到4且狀態爲200時,您最可能要檢查數據。欲瞭解更多信息,請參閱here

您還需要爲您的請求設置內容類型標題。

嘗試這樣:

this.sendPost = function(JodelPost) 
{ 
    var httpRequest = new XMLHttpRequest(); //create new httpRequest 
    httpRequest.onreadystatechange = function() 
    { 
     if (xhttp.readyState == 4 && xhttp.status == 200) 
     { 
      console.log(httpRequest.responseText); 
     } 
    } 

    var url = 'https://api.go-tellm.com/api/v2/posts/?'; //BaseUrl for jodel api 

    httpRequest.open('POST', url); 
    httpRequest.setRequestHeader('Authorization', 'Bearer ' + this.token); 
    httpRequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); 
    httpRequest.send(JSON.stringify(JodelPost)); 
}; 
+0

太謝謝你了! – Shroom

+0

不客氣。快樂編程! – stevenelberger