Access-Control-Allow-Origin不起作用Google Cloud Functions GCF

Enc*_*der 9 javascript ajax node.js cors google-cloud-functions

我觉得这里是个新手,但我正在尝试从浏览器运行一个简单的AJAX请求来访问GCF并且Chrome正在报告:

XMLHttpRequest无法加载 https://us-central1-bustling-opus-830.cloudfunctions.net/Authenticate.请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许来源" https://beast.reachboarding.com.au "访问.

我有一个名为Authenticate的函数(如上所示)正在使用一个名为:

bustling-opus-830.appspot.com
Run Code Online (Sandbox Code Playgroud)

我使用gsutil使用以下JSON文件设置CORS:

[{
    "origin": ["https://beast.localdev.com.au","*"],
    "responseHeader": ["Content-Type"],
    "method": ["GET", "HEAD", "DELETE", "OPTIONS"],
    "maxAgeSeconds": 3600
}]
Run Code Online (Sandbox Code Playgroud)

使用以下命令:

gsutil cors set cors.json gs://bustling-opus-830.appspot.com/
Run Code Online (Sandbox Code Playgroud)

然后从相应的get命令获取以下输出:

gsutil cors get gs://bustling-opus-830.appspot.com/

[{"maxAgeSeconds": 3600, "method": ["GET", "HEAD", "DELETE", "OPTIONS"], "origin": ["https://beast.localdev.com.au", "*"], "responseHeader": ["Content-Type"]}]
Run Code Online (Sandbox Code Playgroud)

我正在使用创建新函数时提供的默认示例代码,如下所述:

/**
 * Responds to any HTTP request that can provide a "message" field in the body.
 *
 * @param {!Object} req Cloud Function request context.
 * @param {!Object} res Cloud Function response context.
 */
exports.helloWorld = function helloWorld(req, res) {
    // Example input: {"message": "Hello!"}
    if (req.body.message === undefined) {
        // This is an error case, as "message" is required.
        res.status(200).send('No message defined!');
    } else {
        // Everything is okay.
        console.log(req.body.message);
        res.status(200).send(req.body.message);
    }
};
Run Code Online (Sandbox Code Playgroud)

以及带有以下Javascript的简单HTML:

$.ajax({
    url: "https://us-central1-bustling-opus-830.cloudfunctions.net/Authenticate",
    type: "POST",
    data: {
        message: 'Testing'
    },
    dataType: 'json', 
    success: function (response) {
        console.log(response);
    },
    error: function (xhr, status) {
        console.log(xhr);
    }
});
Run Code Online (Sandbox Code Playgroud)

这是导致错误的原因.

在我的DEV控制台中,我可以看到网络请求通过.以下是我得到的HTTP响应标头:

cache-control:private
content-encoding:gzip
content-length:27
content-type:text/html; charset=utf-8
date:Wed, 08 Feb 2017 03:45:50 GMT
etag:W/"7-274e639a"
function-execution-id:azc1zqfb1tq8
server:Google Frontend
status:200
vary:Accept-Encoding
x-cloud-trace-context:70e08d634a9644c32530326de0471a64;o=1
x-cloud-trace-context:70e08d634a9644c32530326de0471a64
x-powered-by:Express
Run Code Online (Sandbox Code Playgroud)

我本来希望在响应标题中看到Access-Control-Allow-Origin标头,表明它允许*但我肯定没有看到它.

但疯狂的是,当我查看网络项目并点击响应时,我得到:

Testing
Run Code Online (Sandbox Code Playgroud)

这表明所有事情都是平等的,它实际上是跑了!

我很抱歉,如果之前已经回答过,但我已经搜索了许多不同的关键字,似乎没有解决我的问题.我认为对这个问题(以及一些体面的专业知识)有一双新的眼光会有所帮助.

提前致谢!

小智 22

您的前台(HTTP)Google Cloud Function需要在对AJAX客户端请求的响应中设置适当的CORS标头.HTTP函数的请求和响应参数具有与相应ExpressJS对象等效的属性,可用于设置CORS标头并根据需要响应预检请求.

例如:

exports.Authenticate = function Authenticate (req, res) {
    //set JSON content type and CORS headers for the response
    res.header('Content-Type','application/json');
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type');

    //respond to CORS preflight requests
    if (req.method == 'OPTIONS') {
        res.status(204).send('');
    }

    //continue function ...

};
Run Code Online (Sandbox Code Playgroud)

上面的标题和逻辑应该被修改以反映您的服务的特定需求,但应该有助于您开始.

  • Ryan你死了传奇!我简直不敢相信这是多么简单.我添加了标题并点击刷新,它会立即按预期执行.非常感谢! (2认同)

noo*_*oob 7

您也可以cors按照 Google 的建议使用该软件包来解决此问题。事实上,他们也在自己的示例代码中使用了这一点。检查这个例子。这是代码 -

const cors = require('cors')({
    origin: true,
});

//Your code here

//Use the following function instead of just res.send. return keyword is not compulsory here
return cors(req, res, () => {
    res.send();
});
Run Code Online (Sandbox Code Playgroud)