ColinFay/brochure

Strange EOF issue when POSTing JSON

Closed this issue · 1 comments

Hi! I was working on an example of using brochure to handle post requests, and I noticed a weird error when sending JSON. The following simple app:

library(shiny)
library(jsonlite)
library(brochure)

number_vector <- numeric(0)

main_page <- page(
  href = "/",
  req_handlers = list(
    function(req){
      if (identical(req$REQUEST_METHOD, "POST")) {
        return(httpResponse(200, "text/plain", "OK\n"))
        data <- req$rook.input$read(-1)
        data <- jsonlite::fromJSON(rawToChar(data))
        message(paste0("Received post request with number: ", data$number))
        number_vector <<- c(number_vector, data$number)
        return(httpResponse(200, "text/plain", "OK\n"))
      } else {
        return(req)
      }
    }
  ),
  ui = h2("Numbers received:", textOutput("number_vector", inline = TRUE, container = span)),
  server = function(input, output, session) {
    recheck <- reactiveTimer(500)
    output$number_vector <- renderText({
      recheck() #this causes the number_total to get polled again
      paste0(number_vector, collapse = ", ")
    })
  }
)

brochureApp(
  main_page
)

Gives an error when POSTing JSON. Interestingly, the app works as intended but for some reason the POST returns a 500 error still. I think somehow an EOF is occurring in the data <- req$rook.input$read(-1) line, and that gets returned instead of the success:

> httr::POST('http://127.0.0.1', body = '{"number": 3}\n\n', encode = 'json')

Yields

Response [http://127.0.0.1]
  Date: 2022-07-28 03:06
  Status: 500
  Content-Type: text/plain; charset=UTF-8
  Size: 116 B
ERROR: parse error: premature EOF

Thanks!

I'm closing this because somehow restarting RStudio fixed it. I have no idea why!