1

I have REST API made with Python, and i want to use it via JavaScript. The API needs some data to be send from the the front-end as JSON, so i make the call like this:

var xhttp = new XMLHttpRequest(),
    dataToSend = '{"key":"value"}';

xhttp.onreadystatechange = function() {
    // Some logic.....
};

xhttp.open("POST", "URL to the API", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(dataToSend);

From the server i get 500 with this as reason:

"TypeError: the JSON object must be str, not 'dict'"

I tried to change the MIME type to be "text/plain", "text/html" and several others but it just changed the response to:

TypeError: the JSON object must be str, not 'NoneType'

The back-end people, said that the API works fine, and that they tested it with the following python code

request_result = requests.post('API URL', json=request_data_jsn).json();

Any idea what can I do so that it works?

3
  • "the following python code" is meaningless if we don't know exactly what request_data_jsn is. Also, "application/json" IS the correct content-type header if you're sending json - but what you're sending in your code example is NOT json (json is a text format), it's a javascript object. Commented Dec 20, 2018 at 10:23
  • About the python code, sorry that is all i managed to got from them. About the object, it actually is valid JSON string, it have all the quotation sings and all. I allso validate it with jsonlint.com to make sure it is correct format Commented Dec 20, 2018 at 10:31
  • The comment about what you're sending not being proper json was from what I saw before you edited your question actually - the edited version seems correct. wrt/ the python side, you'll have to ask the "backend guys" for a proper complete example else there's no way to help with this. Commented Dec 20, 2018 at 11:10

1 Answer 1

3

You must convert dataToSend to string. Example: using JSON.stringify

var xhttp = new XMLHttpRequest(),
    dataToSend = {"key":"value"}

xhttp.onreadystatechange = function(data) {
    console.log(data);
};

dataToSend = JSON.stringify(dataToSend);
xhttp.open("POST", "URL to the API", true)
xhttp.setRequestHeader("Content-type", "application/json")
xhttp.send(dataToSend);
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry i did not write my question right, i did do actually that (i just edited my question)
I tried your code: dataToSend = '{"key":"value"}'. It is success. Can you put python API code?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.