简体   繁体   中英

XML HTTP request Jodel

I have spent alot of hours trying to solve this on my own and can't find the solution.

This is a function inside my jodelclient object.

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! 
};

The response from the server is

"POST https://api.go-tellm.com/api/v2/posts/ ? 400 (Bad Request)"

and

"Missing required property: location"

this is an example of the result of stringifying the JodelPost variable.

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

When I was trying to solve this for myself I found this github repository doing the same thing but in python. It might be some useful information in there.

Pydel

Thanks in advance! I am quite new to this so simple explanations are appreciated.

Looks to me like the request isn't being created correctly. You're trying to send the data with the URL, but it should be passed in the XHR object's send function.

Also, the onreadystatechange function gets called each time the state changes, but you most likely want to check for the data when the state reaches 4 and the status is 200 . For more reading, see here .

You'll also want to set the content-type header for your request.

Try something like this:

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));
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM