gpt4 book ai didi

go - Google Cloud Function不返回我使用Go设置的CORS header

转载 作者:行者123 更新时间:2023-12-01 22:15:05 24 4
gpt4 key购买 nike

我意识到也有类似的问题(例如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应用程序调用cloud函数时,出现以下错误: 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).

最佳答案

这是您的云功能应具有的标准格式。它应该检查预检请求发送的OPTIONS方法并设置希瑟石楠。然后,它应发送希瑟石作为主要要求。

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

HTTP Functions

// 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!")
}


关于go - Google Cloud Function不返回我使用Go设置的CORS header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60856627/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com