简体   繁体   中英

Send form data as json to a server

I have a server running that accepts a POST request with input in the form of json. Now, I am trying to create a simple html page that will trigger the POST request once the user clicks on Submit button. My code is as follows

<!DOCTYPE html>
<html>
<br/><br/><br/><br/>
<body>
<script>
function submitform (form) {
   var object = {};
   form.forEach((value, key) => {object[key] = value});
   var json = JSON.stringify(object);
   return json;
}

</script>
<form action="http://localhost:9000/parse" method="post">

    <h3>Enter url :</h3>
    <input type="text" name="url" placeholder="http://google.com" style="width: 300px"><br>
    <br/><br/>
    <input type="submit" name="Get Website Statistics" style="width: 20em;  height: 2em;" onclick="submitform()">
</form>
</body>
</html>

I want the server to receive the request with payload

{
    "url" : "https://www.example.com"
}

However, I receive the response from server as

For request 'POST /parse' [Expecting text/json or application/json body]

My curl request is as follows

curl 'http://localhost:9000/parse' -H 'Connection: keep-alive' -H 'Cache-Control: max-age=0' -H 'Origin: http://localhost:63342' -H 'Upgrade-Insecure-Requests: 1' -H 'Content-Type: application/x-www-form-urlencoded' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36' -H 'Sec-Fetch-User: ?1' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3' -H 'Sec-Fetch-Site: same-site' -H 'Sec-Fetch-Mode: navigate' -H 'Referer: http://localhost:63342/html-parser/views/index.html' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: en-GB,en;q=0.9,en-US;q=0.8' -H 'Cookie: Idea-836ae252=9c616505-7e0e-4a1e-bdd0-fa54e473c071' --data 'url=https%3A%2F%2Fwww.spiegel.de%2Fmeinspiegel%2Flogin.html&Get+Website+Statistics=Submit' --compressed

Can anybody please guide me as to what I am doing wrong here? TIA

Apparently you didn't include your JSON into the body:

 <form action="localhost:9000/parse" method="post"> <h3>Enter url:</h3> <input type="text" name="url" placeholder="http://google.com" style="width: 300px"><br> <br/><br/> <input type="submit" name="Get Website Statistics" style="width: 20em; height: 2em;"> </form>

 <form action="http://localhost:9000/parse" method="post" onsubmit="return submitform()">
   <input type="submit" name="Get Website Statistics" style="width: 20em;  height: 2em;">
 </form>

put onsubmit event inside a form tag.

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