How to send AND receive POST requests with JavaScript HTML


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

    let data = {element: "barium"};
    fetch("http://localhost:5000/newCheckout", {
      method: "POST", 
      body: JSON.stringify(data)
    }).then(res => {
      console.log("Request complete! response:", res);

and received it with (Python/Flask): element = request.form.get(‘element’)
did not work

Thanks in advance!


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

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published