Symptoms:
When launching an application in Posit Connect, the user receives the below error.
An error has occurred!
An error has occurred. Check your logs or contact the app author for clarification.
CORS is enabled in rstudio-connect.gcfg.
[CORS]
Enabled = true
Explanation:
Even if Connect is configured to have CORS enabled, it might be that the application still needs to account for the preflight OPTIONS request. When content hosted in Connect is responsible for handling requests and issue responses, sometimes such content needs to be adjusted so it allows CORS as well.
- When CORS communicates with Connect
- When Connect hands over requests to published content
Workaround:
First, broaden the permissions for the CORS parameter in /etc/rstudio/rstudio-connect.gcfg.
[CORS]
Enabled = true
AllowOrigin = *
EnforceWebsocketOrigin = false
You will need to restart Posit Connect after making this change.
systemctl restart rstudio-connect
Next, somewhere inside the R code for your application, you will need to add "OPTIONS" as a supported HTTP method. The response from the "OPTIONS" request needs to be a 200
and include the following headers:
"Access-Control-Allow-Origin: *"
"Access-Control-Allow-Methods: DELETE, POST, GET, OPTIONS, PUT, HEAD"
"Access-Control-Allow-Headers: *"
Finally, you will need to call these headers into the body of your code. The below example uses the Plumber API, but you will need to customize this for your specific code and use case.
#' @filter cors
cors <- function(req, res) {
res$setHeader("Access-Control-Allow-Origin", "*")
if (req$REQUEST_METHOD == "OPTIONS") {
res$setHeader("Access-Control-Allow-Methods","*")
res$setHeader("Access-Control-Allow-Headers", "*")
res$setHeader("Access-Control-Allow-Credentials", "true")
res$status <- 200
return(list())
} else {
plumber::forward()
}
}
Comments