pkulchenko / fullmoon

Fast and minimalistic Redbean-based Lua web framework in one file.
MIT License
684 stars 30 forks source link

Getting the body of the request #9

Closed rashadg1030 closed 2 years ago

rashadg1030 commented 2 years ago

Probably overlooking something on my end, but I'm unable to get the response body for some reason. I have a handler defined like so:

local function handleTarget(request)
  print("Handling target")
  print("Body: "..request.body)
  ...
end

fullmoon.setRoute("/*",
  function (request)
    print("SET OPTIONS")
    request.headers["Access-Control-Allow-Origin"] = "*"
    if request.method == "OPTIONS" then
      return fullmoon.serveResponse(200, "")
    end
    return false
  end
)

fullmoon.setRoute("/:target", handleTarget)

When sending a request without a body everything works fine; I get a 200 response. When I attach a body to the request it seems to trigger a CORS issue for some reason. Also, request.body returns nil. Using redbean's GetBody() didn't work either. I'm using hoppscotch.io to test the API.

pkulchenko commented 2 years ago

@rashadg1030, I do get the expected result with the following code:

local fullmoon = require"fullmoon"

local function handleTarget(request)
  print("Handling target")
  print("Body: "..request.body)
  return true
end

fullmoon.setRoute("/*",
  function (request)
    print("SET OPTIONS")
    request.headers["Access-Control-Allow-Origin"] = "*"
    if request.method == "OPTIONS" then
      return fullmoon.serveResponse(200, "")
    end
    return false
  end
)

fullmoon.setRoute("/:target", handleTarget)

fullmoon.run()

When I call with with curl -X POST -H "Content-Type: application/json" -d "{ \"key1\": \"value1\" }" http://localhost:8080/sometarget, I see the following printed as expected:

Handling target
Body: { "key1": "value1" }

If you're talking specifically about responding to a pre-flight CORS request, then instead of returning 200, you should do something like this (according to MDN docs):

    if request.method == "OPTIONS" then
      request.headers["Access-Control-Allow-Origin"] = "*"
      request.headers["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS, DELETE" -- whatever you accept
      return fullmoon.serve204
    end
rashadg1030 commented 2 years ago

@pkulchenko I also needed to add request.headers["Access-Control-Allow-Headers"] = "*" and it works perfectly. I wasn't handling the pre-flight request correctly. Now POST requests to my API work as expected, and request.body has the expected value. Thank you for your help.

pkulchenko commented 2 years ago

Sounds good; thank you for the update!