Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in GCP by (19.7k points)
recategorized by

I just finished the Hello World Google Cloud Functions tutorial and received the following response headers:

Connection → keep-alive

Content-Length → 14

Content-Type → text/plain; charset=utf-8

Date → Mon, 29 Feb 2016 07:02:37 GMT

Execution-Id → XbT-WC9lXKL-0

Server → nginx

 How can I add the CORS headers to be able to call my function from my website?

closed

1 Answer

+1 vote
by (62.9k points)
selected by
 
Best answer

I will start with the assumption that you already know how to set up a cloud function. For instance, let’s say your cloud function calls a third-party API to fetch some data and uses/ filters it in some way before sending it to you. Me being a fan of Space X, let's say I will be fetching data about the next Space X launch.

import flask

import requests

def getUserDetails(request):

user = requests.get('https://api.spacexdata.com/v3/launches/next'

                        ).json()

response = flask.jsonify(user)

response.headers.set('Access-Control-Allow-Origin', '*')

response.headers.set('Access-Control-Allow-Methods', 'GET, POST')

return response

As you can see in these two lines.

response.headers.set('Access-Control-Allow-Origin', '*') response.headers.set('Access-Control-Allow-Methods', 'GET, POST')

I’m setting the CORS to allow all origins ( of course you can change this ). And they only allow GET and POST methods.

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...