RealTimeLogic / BAS

Embedded Web Server Library with Integrated Scripting Engine
https://realtimelogic.com/products/barracuda-application-server/
GNU General Public License v2.0
61 stars 14 forks source link

How get body of the request from fetch of a json data #1

Closed vespadj closed 2 years ago

vespadj commented 2 years ago

Please, provide an example for getting the body of the request when using fetch method.

// request options
const options = {
    method: 'POST',
    body: JSON.stringify(myCustomData),
    headers: {
        'Content-Type': 'application/json'
    }
}

// send POST request
fetch(url, options)
    .then(res => res.json())
    .then(res => console.log(res));

I try

-- display all posted values
for name,value in request:datapairs() do
  print(name,'=',value)
end

but the result is empty.

ECMA6 Fetch function is explained here.

Thanks

vespadj commented 2 years ago

... trying

for data in request:rawrdr() do
  trace("request:rawrdr()", data)
end

It seem good

surfskidude commented 2 years ago

Yes, use this template code:

<?lsp
if "application/json" == request:header"Content-Type" then
   local jparser = ba.json.parser()
   local ok,table
   for data in request:rawrdr() do
      ok,table=jparser:parse(data)
      if not ok or table then break end
   end
   trace(ok, table)
   if ok and table then
      response:json(table)
   end
   response:senderror(400, "Invalid JSON")
end
?>
<html>
<script>
const data={
   weekdays:
     ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
  }
fetch(location.href, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
        'Content-Type': 'application/json'
    }
 }).then(res => res.json())
   .then(res => console.log(res));
</script>
</html>