当前位置: > > > > Google Cloud Function 不返回我使用 Go 设置的 CORS 标头
Google Cloud Function 不返回我使用 Go 设置的 CORS 标头
来源:stackoverflow
2024-04-27 10:06:51
0浏览
收藏
米云今天将给大家带来《Google Cloud Function 不返回我使用 Go 设置的 CORS 标头》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!
问题内容
我意识到存在类似的问题(例如 google cloud functions 启用 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 disallowsread the remote resource at https://us-central1-my- function.cloudfunctions.net/myfunction。 (原因:缺少 cors 标头“access-control-allow-origin”).
解决方案
这是您的云函数应该具有的标准形式。它应该检查预检请求发送的 options 方法并设置 heathers。然后它应该发送主要请求的石南花。
在这里您可以找到更多信息:
// 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!")
}
以上就是《Google Cloud Function 不返回我使用 Go 设置的 CORS 标头》的详细内容,更多关于的资料请关注米云公众号!
