ssk
ssk

Reputation: 9255

How to enable CORS on Google App Engine Python Server?

I am see the following error on Javascript console:

VM31:1 XMLHttpRequest cannot load '<some-url>'. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '<my-url>' is therefore not allowed access.

How do I enable Cross-Origin Resource Sharing with Google App Engine (Python) to access ?

Upvotes: 11

Views: 14459

Answers (4)

GregK
GregK

Reputation: 593

If you want to serve a script, you cannot use Jeffrey Godwyll's answer, unfortunately. The documentation, somewhat hidden in the second sentence of the http_headers states: "If you need to set HTTP headers in your script handlers, you should instead do that in your app's code."

Another possibility is to allow your app to handle pre-flight requests by "prematurely" returning the headers. GOTCHA: If you are building a POST endpoint, make it so that it returns the allow cross site origin request headers on everything BUT your desired request method. Sometimes there may be a pre-flight GET as well (for some odd reason):

from flask import Flask, request

HEADERS = {
    "Access-Control-Allow-Origin": "*",
}

app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def main():
    if request.method != "POST":
        return ("", 204, HEADERS)

    return "After the POST"

If you are building an app for GET only, you can instead write if request.method == "OPTIONS":..., like in the Cloud Functions documentation

Upvotes: 0

Shabirmean
Shabirmean

Reputation: 2571

For those who are wondering how to basically allow all origins for the AppEngine instance in Springboot:

  • use the @CrossOrigin(origins = "*") annotation on the @RestController classes your project has
  • or use use the same annotation above for any of your specific resource methods that has one of the @GetMapping, @PostMapping, etc annotations.

No need to set any of the handlers in the app.yaml. Actually it didn't work when changing the app.yaml file as explained in the docs

...
...
...

@SpringBootApplication
@RestController
@CrossOrigin(origins = "*")  // <--- here 
public class SpringbootApplication {

 ...
 ...
  @GetMapping("/")      
  @CrossOrigin(origins = "*").     // <--- or here 
  public String hello() {
      .....
  }

}

Upvotes: 1

Jeff
Jeff

Reputation: 1335

For a python script you can add the following line near other self.response.header lines.

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

This worked for me. The idea was taken from a php issue listed in the notes of another answer.

Upvotes: 11

Jeffrey Godwyll
Jeffrey Godwyll

Reputation: 3893

You'll have to use the Access-Control-Allow-Origin http header in your yaml configuration

handlers:
- url: /
  ...
  http_headers:
    Access-Control-Allow-Origin: http://my-url

Find more under CORS Support in the docs

Upvotes: 11

Related Questions