简体   繁体   English

谷歌云功能启用 CORS?

[英]Google Cloud Functions enable CORS?

I just finished the Hello World Google Cloud Functions tutorial and received the following response headers:我刚刚完成 Hello World Google Cloud Functions 教程并收到以下响应标头:

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?如何添加 CORS 标头以便能够从我的网站调用我的 function?

here we go:开始了:

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

  if (req.method === "OPTIONS") {
    // stop preflight requests here
    res.status(204).send('');
    return;
  }

  // handle full requests
  res.status(200).send('weeee!);
};

then you can jquery/whatever it as usual:然后你可以像往常一样jquery/什么:

$.get(myUrl, (r) => console.log(r))

I'm the product manager for Google Cloud Functions.我是 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.我们目前还没有什么要宣布的,但我们知道需要对 Cloud Functions 的 HTTP 调用功能进行几项增强,我们将在未来的迭代中对此和许多其他领域进行改进。

UPDATE:更新:

We've improved the way you deal with HTTP in Cloud Functions.我们改进了您在 Cloud Functions 中处理 HTTP 的方式。 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 )您现在可以完全访问 HTTP 请求/响应对象,因此您可以设置适当的 CORS 标头并响应飞行前 OPTIONS 请求 ( https://cloud.google.com/functions/docs/writing/http )

如果您正在寻找一个实际的代码示例(并且您的问题仍然相关),我写了一篇关于它的博客文章: https//mhaligowski.github.io/blog/2017/03/10/cors-in-cloud- functions.html

You can use the CORS express middleware.您可以使用 CORS express 中间件。

package.json包.json

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

index.js索引.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);

I've just created webfunc .我刚刚创建了webfunc It's a lightweight HTTP server that supports CORS as well as routing for Google Cloud Functions.它是一个轻量级的 HTTP 服务器,支持 CORS 以及 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:在项目的根目录中,只需添加如下所示的appconfig.json

{
  "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.希望这可以帮助。

You need to send an 'OPTIONS' response by setting its header as follows:您需要通过如下设置其标头来发送'OPTIONS'响应:

if (req.method === 'OPTIONS') {
  res.set('Access-Control-Allow-Methods', '*');
  res.set('Access-Control-Allow-Headers', '*');
  res.status(204).send('');
}

Runtime: NodeJS 10运行时:NodeJS 10

If you tried the accepted answer but encountered a preflight error, the docs offer examples of handling it in multiple languages, with the caveat that it only works on public functions, ie deployed with --allow-unauthenticated :如果您尝试了接受的答案但遇到了预检错误, 文档提供了以多种语言处理它的示例,但需要注意的是它仅适用于公共功能,即使用--allow-unauthenticated部署:

exports.corsEnabledFunction = (req, res) => {
  res.set("Access-Control-Allow-Origin", "*");

  if (req.method === "OPTIONS") {
    /* handle preflight OPTIONS request */
    
    res.set("Access-Control-Allow-Methods", "GET, POST");
    res.set("Access-Control-Allow-Headers", "Content-Type");

    // cache preflight response for 3600 sec
    res.set("Access-Control-Max-Age", "3600");
    
    return res.sendStatus(204);
  }

  // handle the main request
  res.send("main response");
};

In the python environment, you can use the flask request object to manage CORS requests.在python环境下,可以使用flask请求对象来管理CORS请求。

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.有关更多信息,请参阅gcloud 文档

You must enable CORS within all your functions, for example hello function:您必须在所有函数中启用 CORS,例如 hello 函数:

index.js索引.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

package.json包.json

{
  "name": "function-hello",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "cors": "^2.8.5"
  }
}

After applying your favourite answer from here, if you're still getting this error, check for uncaught errors in your cloud function. This can result in the browser receiving a CORS error, even when your error has nothing to do with CORS从此处应用您最喜欢的答案后,如果您仍然收到此错误,请检查云 function 中是否存在未捕获的错误。这可能导致浏览器收到 CORS 错误,即使您的错误与 CORS 无关

After CORS enabled if you send POST request to your function also check for your request Content-Type header, mine was set it to "text/plain" and my browser was constantly triggering CORS errors, after setting the header to "application/json" everything worked properly.启用 CORS 后,如果您向 function 发送 POST 请求,还要检查您的请求 Content-Type header,我的设置为“text/plain”,在将 header 设置为“application/json”后,我的浏览器不断触发 CORS 错误一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM