Google Cloud Functions enable CORS?

后端 未结 6 1667
暖寄归人
暖寄归人 2020-12-05 17:08

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

Connection → keep-alive
Content-Length → 14
Cont         


        
相关标签:
6条回答
  • 2020-12-05 17:35

    In the python environment, you can use the flask request object to manage CORS requests.

    def cors_enabled_function(request):
        if request.method == 'OPTIONS':
            # Allows GET requests from any origin with the Content-Type
            # header and caches preflight response for an 3600s
            headers = {
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'GET',
                'Access-Control-Allow-Headers': 'Content-Type',
                'Access-Control-Max-Age': '3600'
            }
    
            return ('', 204, headers)
    
        # Set CORS headers for the main request
        headers = {
            'Access-Control-Allow-Origin': '*'
        }
    
        return ('Hello World!', 200, headers)
    

    See the gcloud docs for more.

    0 讨论(0)
  • 2020-12-05 17:37

    I've just created webfunc. It's a lightweight HTTP server that supports CORS as well as routing for Google Cloud Functions. Example:

    const { serveHttp, app } = require('webfunc')
    
    exports.yourapp = serveHttp([
      app.get('/', (req, res) => res.status(200).send('Hello World')),
      app.get('/users/{userId}', (req, res, params) => res.status(200).send(`Hello user ${params.userId}`)),
      app.get('/users/{userId}/document/{docName}', (req, res, params) => res.status(200).send(`Hello user ${params.userId}. I like your document ${params.docName}`)),
    ])
    

    In your project's root, simply add a appconfig.json that looks like this:

    {
      "headers": {
        "Access-Control-Allow-Methods": "GET, HEAD, OPTIONS, POST",
        "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Max-Age": "1296000"
      }
    }
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-05 17:37

    You must enable CORS within all your functions, for example hello function:

    index.js

    const cors = require('cors')();
    
    // My Hello Function
    function hello(req, res) {
      res.status(200)
        .send('Hello, Functions');
    };
    
    // CORS and Cloud Functions export
    exports.hello = (req, res) => {
      cors(req, res, () => {
        hello(req, res);
      });
    }
    

    Don't forget about package.json

    package.json

    {
      "name": "function-hello",
      "version": "0.1.0",
      "private": true,
      "dependencies": {
        "cors": "^2.8.5"
      }
    }
    
    0 讨论(0)
  • 2020-12-05 17:40

    You can use the CORS express middleware.

    package.json

    npm install express --save
    npm install cors --save
    

    index.js

    'use strict';
    
    const functions = require('firebase-functions');
    const express = require('express');
    const cors = require('cors')({origin: true});
    const app = express();
    
    app.use(cors);
    app.get('*', (req, res) => {
        res.send(`Hello, world`);
    });
    
    exports.hello = functions.https.onRequest(app);
    
    0 讨论(0)
  • 2020-12-05 17:50

    here we go:

    exports.helloWorld = function helloWorld(req, res) {  
      res.set('Access-Control-Allow-Origin', "*")
      res.set('Access-Control-Allow-Methods', 'GET, POST')
      res.status(200).send('weeee!);
    };
    

    then you can jquery/whatever it as usual:

    $.get(myUrl, (r) => console.log(r))
    
    0 讨论(0)
  • 2020-12-05 18:01

    I'm the product manager for Google Cloud Functions. Thanks for your question, this has been a popular request.

    We don't have anything to announce just yet, but we're aware of several enhancements that need to be made to the HTTP invocation capabilities of Cloud Functions and we'll be rolling out improvements to this and many other areas in future iterations.

    UPDATE:

    We've improved the way you deal with HTTP in Cloud Functions. You now have full access to the HTTP Request/Response objects so you can set the appropriate CORS headers and respond to pre-flight OPTIONS requests (https://cloud.google.com/functions/docs/writing/http)

    0 讨论(0)
提交回复
热议问题