swifter
swifter copied to clipboard
Support for CORS
Hello,
Any plans for adding CORS support (so that it is possible to make web calls to the iOS app from javascript in a modern browser [without disabling the same-origin policy of the browser])?
Thanks!
You can just add the CORS headers e.g.:
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: http://example.com:8080
See more here: https://www.w3.org/wiki/CORS_Enabled
@nrmtrifork: It is not quite that simple. The browser does a pre-flight check by sending an HTTP OPTIONS request to the site (in this case Swifter), before sending the actual HTTP request (and it will not send the actual request if "approval" was not received from the site).
How do you respond to the OPTIONS request and how do you add the CORS headers with Swifter?
More data: Wikipedia on CORS
I know about the pre-flight check. However, this works for me:
private static func corsDecorate(var response : HttpResponse) -> HttpResponse { response = setHeadersOnResponse(response, headersToAdd:[ "Access-Control-Allow-Origin":"*", "Access-Control-Allow-Methods":"GET, POST, OPTIONS", "Access-Control-Allow-Headers":HEADER_KEY_CONTENT_TYPE ]) return response }
@nrmtrifork Thanks, I'll check it out.
Is it possible @nrmtrifork could explain where I need to put that function to call and set those headers?
Right now I am trying to set the headers on scopes as that is what I'm using. Similar to the demo server.
public func scopes(_ scope: @escaping Closure) -> ((HttpRequest) -> HttpResponse) { return { r in ScopesBuffer[Process.tid] = "" scope() return .raw(200, "OK", ["Content-Type": "text/html", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"], { try? $0.write([UInt8](("<!DOCTYPE html>" + (ScopesBuffer[Process.tid] ?? "")).utf8)) }) } }
Should that work. I see the headers. But I'm still getting the "Origin address is not allowed by Access-Control-Allow-Origin".
Bump?
Has anyone found a solution for this? To set the CORS I need to create an OPTIONS route, but that doesn't seem to be supported.