为了账号安全,请及时绑定邮箱和手机立即绑定

Google Cloud Function 不返回我使用 Go 设置的 CORS 标头

Google Cloud Function 不返回我使用 Go 设置的 CORS 标头

Go
慕斯王 2022-05-23 16:31:26
我意识到有类似的问题(例如Google Cloud Functions enable CORS?),但他们的答案似乎对我不起作用。Google Cloud Function 具有以下响应代码:func HelloWorld(w http.ResponseWriter, r *http.Request) {    [...]    response := make(map[string]interface{})    w.WriteHeader(http.StatusOK)    w.Header().Set("Content-Type", "application/json")    w.Header().Set("Access-Control-Allow-Origin", "*")    w.Header().Set("Allow", "GET, OPTIONS")    w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")    w.Header().Set("Access-Control-Allow-Headers", "*")    response["list"] = list    if err = json.NewEncoder(w).Encode(response); err != nil {        fmt.Println(err)    }}通常我认为它就足够了Access-Control-Allow-Origin", "*",但由于它不起作用,所以我也包括了其他人。当我尝试时,curl -v "https://us-central1-my-function.cloudfunctions.net/myfunction"我得到以下响应:[...]* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):* old SSL session ID is stale, removing* Connection state changed (MAX_CONCURRENT_STREAMS == 100)!< HTTP/2 200 < content-type: text/plain; charset=utf-8< function-execution-id: ivz4zonw37d1< x-cloud-trace-context: b6929d3ddf88dc102f6f1f069404aeaa;o=1< date: Wed, 25 Mar 2020 20:00:52 GMT< server: Google Frontend[...]当我尝试从本地 vuejs 应用程序调用云函数时,出现以下错误:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://us-central1-my-function.cloudfunctions.net/myfunction. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
查看完整描述

1 回答

?
元芳怎么了

TA贡献1798条经验 获得超7个赞

这是你的云功能应该有的标准形式。它应该检查预检请求发送的 OPTIONS 方法并设置石南花。然后它应该为主要请求发送石南花。

在这里您可以找到更多信息:

// Package http provides a set of HTTP Cloud Functions samples.

package http


import (

        "fmt"

        "net/http"

)


// CORSEnabledFunction is an example of setting CORS headers.

// For more information about CORS and CORS preflight requests, see

// https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request.

func CORSEnabledFunction(w http.ResponseWriter, r *http.Request) {

        // Set CORS headers for the preflight request

        if r.Method == http.MethodOptions {

                w.Header().Set("Access-Control-Allow-Origin", "*")

                w.Header().Set("Access-Control-Allow-Methods", "POST")

                w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

                w.Header().Set("Access-Control-Max-Age", "3600")

                w.WriteHeader(http.StatusNoContent)

                return

        }

        // Set CORS headers for the main request.

        w.Header().Set("Access-Control-Allow-Origin", "*")

        fmt.Fprint(w, "Hello, World!")

}


查看完整回答
反对 回复 2022-05-23
  • 1 回答
  • 0 关注
  • 109 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号