Skip to content

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

Closed

Description

@vespadj

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

Activity

  1. vespadj commented on Mar 14, 2022

    @vespadj
    Author

    ... trying

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

    It seem good

  2. surfskidude commented on Mar 14, 2022

    @surfskidude
    Collaborator

    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>
    
  3. locked and limited conversation to collaborators on Mar 14, 2022
  4. converted this issue into a discussion #2 on Mar 14, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions