swifter icon indicating copy to clipboard operation
swifter copied to clipboard

Support for CORS

Open Laban1 opened this issue 9 years ago • 7 comments

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!

Laban1 avatar Jul 06 '16 15:07 Laban1

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 avatar Jul 06 '16 15:07 nrmtrifork

@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

Laban1 avatar Jul 06 '16 15:07 Laban1

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 avatar Jul 07 '16 07:07 nrmtrifork

@nrmtrifork Thanks, I'll check it out.

Laban1 avatar Jul 07 '16 16:07 Laban1

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".

tim-9red7 avatar Oct 20 '16 17:10 tim-9red7

Bump?

tim-9red7 avatar Nov 04 '16 15:11 tim-9red7

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.

Joebayld avatar Jun 12 '20 11:06 Joebayld