swhitty/FlyingFox

Cross-Origin

Bella-Tim opened this issue · 2 comments

When it comes to cross-origin requests, I've noticed that the requests don't even reach the server, so I can't set the necessary headers for cross-origin as I usually would. How can I handle this?

private func startListener() async{
    do {
        let headers = [
                       HTTPHeader("Access-Control-Allow-Origin"):"*",
                       HTTPHeader("Access-Control-Allow-Headers"): "*",
                       HTTPHeader("Access-Control-Allow-Methods"): "OPTIONS, GET, POST",
                       HTTPHeader("Access-Control-Allow-Credentials") : "true"
                      ]

          await server.appendRoute("/hook") { request in
          //  Don't receive any message.
          return HTTPResponse(statusCode: .ok,headers: headers)
        }

        try await server.start()

        print("Server is running on port xxxx")

    } catch {
        print("Server start error: \(error)")
    }
}

Hi @Bella-Tim — I'm not an expert in CORS but FlyingFox should support it when the correct headers are returned.

www.whileloop.com/swiftdraw currently makes make cross origin requests to FlyingFox on swiftdraw.whileloop.com via fetch().

The preflight OPTIONS request must be handled returning HTTP 204 along with the CORS headers before the actual request is made. The browser may cache the preflight response so you may need to clear this cache while in development.

Below are the handlers I use on swiftdraw.whileloop.com for this purpose. I hope it helps.

// Required Headers
private extension HTTPHeader {
  static let accessControlAllowOrigin  = HTTPHeader("Access-Control-Allow-Origin")
  static let accessControlAllowMethods = HTTPHeader("Access-Control-Allow-Methods")
  static let accessControlAllowHeaders = HTTPHeader("Access-Control-Allow-Headers")
  static let accessControlMaxAge       = HTTPHeader("Access-Control-Max-Age")
  static let vary                      = HTTPHeader("Vary")
}

// Preflight responds with HTTP 204
await server.appendRoute("OPTIONS /renderPath") { _ in
  HTTPResponse(
    statusCode: .noContent,
    headers: [
	  .accessControlAllowOrigin: "https://www.whileloop.com",
	  .accessControlAllowMethods: "POST, OPTIONS",
	  .accessControlAllowHeaders: "accept, authorization, content-type, origin, x-requested-with, user-agent, access-control-allow-origin",
	  .accessControlMaxAge: "86400",
	  .vary: "Origin"
	]
  )
}

// Handle request 
await server.appendRoute("POST /renderPath") { _ in
  HTTPResponse(
    statusCode: .ok,
    headers: [
	  .accessControlAllowOrigin: "https://www.whileloop.com",
	  .accessControlAllowMethods: "POST",
	  .vary: "Origin",
	  .contentType: "image/svg+xml"
	],
    body: "<svg></svg>".data(using: .utf8)!
  )
}

@swhitty Tried it, it works.