Issue
So I have been searching for some time and have been wondering. How can I add javascript that sends POST data to an external site and how can I make that external site receive it?
I tried
<script>
let data = {element: "barium"};
fetch("http://localhost:5000/newCheckout", {
method: "POST",
body: JSON.stringify(data)
}).then(res => {
console.log("Request complete! response:", res);
});
</script>
and received it with (Python/Flask): element = request.form.get('element') did not work
Thanks in advance!
Solution
You're sending JSON data but trying to retrieve form data in flask. Try using request.json()
in flask instead (See this question on how to receive different data-types in flask).
You may have to set the Content-Type
header to application/json
in javascript for that to work. For example:
fetch("http://localhost:5000/newCheckout", {
method: "POST",
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then(res => {
console.log("Request complete! response:", res);
});
Some more details of what's going on
JSON looks like this: {"x": 1, "y": 2}
form-encoded data looks like this: x=1&y=2
When you send data to a server, you're just sending it a string of characters. You can send anything in that string, but if you're sending a common format, like JSON, or form-encoded data, you will generally set the Content-Type
header too, so the server knows what kind of data it's receiving (This is important, because sometimes a server will support multiple data types).
Flask will inspect the Content-Type header, and parse the data accordingly. They chose to place the resulting data in different locations on the request object depending on the type of data being sent, so you have to make sure you look in the right places to get the desired data.
Right now, you've coded it up so that the client will send a chunk of plain text (you didn't send any specific content-type), and the server is expecting form-encoded data.
Answered By - Scotty Jamison
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.