简体   繁体   中英

Python API, consumed by JavaScript, sending JSON data

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?

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

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