Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use CORS? #57

Closed
minwookH opened this issue Mar 27, 2019 · 4 comments
Closed

How to use CORS? #57

minwookH opened this issue Mar 27, 2019 · 4 comments

Comments

@minwookH
Copy link

I want to call "localhost" from another domain.
How to setting CORS?

@minwookH
Copy link
Author

Sorry.
I success after header.

@yvbeek
Copy link
Member

yvbeek commented Mar 29, 2019

@pmpmopm1 Not a problem. If you are using this in a development scenario you can send the following header back to the client:

Access-Control-Allow-Origin: *

If you want to make it a bit fancier, you can create a handler:

public class HTTPCORSHandler: HTTPRequestHandler {
  public func respond(to request: HTTPRequest, nextHandler: HTTPRequest.Handler) throws -> HTTPResponse? {
    let response = try nextHandler(request)

    // Add access control header for GET requests
    if request.method == .GET { 
      response?.headers["Access-Control-Allow-Origin"] = "*"
    }

    return response
  }
}

For increased security you can add additional checks, dig down into the request, and send back different CORS headers for different clients.

@YiYiZheng
Copy link

Could you pls show the code how to set the header. Thx

@yvbeek
Copy link
Member

yvbeek commented May 10, 2019

@YiYiZheng I've added a section about CORS to the readme:
https://github.com/Building42/Telegraph#http-cross-origin-resource-sharing-cors

If you have a response object, simply set the header with:

response.headers["Access-Control-Allow-Origin"] = "*"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants