【问题标题】:The problem with CORS headers for the server on GoGo 上服务器的 CORS 标头问题
【发布时间】:2019-10-25 07:46:58
【问题描述】:

现在我正在使用标准库 net/http 在 Go 上编写一个简单的服务器。服务器放置在 docker 容器中,并放置在 google cloud paltform 上。但是,当我想从我的第三方 React 应用程序(位于不同的服务器上)访问服务器时,我总是会收到 CORS 错误。

在线寻找解决方案,我在代码中添加了一个库,旨在解决СORS问题。但是添加一个库并没有帮助。即使在其应用之后,服务器也不会向我发送СORS 标头。我现在有什么代码?

package main

import (
    controller "./controllers"
    "./util"
    "github.com/gorilla/mux"
    "github.com/rs/cors"
    "log"
    "net/http"
    //"os"
)

// Entry point
func main() {
    c := cors.New(cors.Options{
        AllowedOrigins: []string{"*"}, // All origins
        AllowedMethods: []string{"GET"}, // Allowing only get, just an example
        AllowedHeaders: []string{"Authorization", "Content-Type"},
        AllowCredentials: true,
        Debug: true,
    })

    r := mux.NewRouter()
    // Router
    // Live check
    r.HandleFunc("/live", controller.LiveCheck)
    apiRouter := r.PathPrefix("/api").Subrouter()
    // Medication data
    medicationRouter := apiRouter.PathPrefix("/medication").Subrouter()
    medicationRouter.HandleFunc("", controller.MedicationHeadersList).Methods("GET")
    medicationRouter.HandleFunc("/{id}", controller.MedicationChildrenList).Methods("GET")
    medicationRouter.HandleFunc("/{id}/leafs", controller.MedicationLeafsList).Methods("GET")
    medicationRouter.HandleFunc("/search/", controller.SearchMedicationList).Methods("GET")
    medicationRouter.HandleFunc("/result/{id}", controller.MedicationSearchResult).Methods("GET")

    //r.Use(util.CORS)
    apiRouter.Use(util.VerifyToken)

    log.Println(http.ListenAndServe(":8080", c.Handler(r)))
}

这是我从浏览器控制台中得到的答案:

Request Method: OPTIONS
Status Code: 200 OK
Remote Address: 35.190.37.37:80
Referrer Policy: no-referrer-when-downgrade
Content-Length: 0
Date: Mon, 10 Jun 2019 22:37:36 GMT
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
Via: 1.1 google

我还尝试手动设置 CORS 标头,创建一个中间件,但它也没有帮助。 提前感谢您的帮助!

UPD感谢大家的回答和帮助。一切都变得容易多了。谷歌没有更新我的 docker 容器,所以我对代码的所有更改都没有达到预期的效果。我在问题描述中给出的代码完美地解决了 CORS 的问题。该问题可以视为已结束。

【问题讨论】:

    标签: google-app-engine go google-cloud-platform


    【解决方案1】:

    我也有这个问题。您可以在开发环境中使用此代码。

        c := cors.New(cors.Options{
            AllowedOrigins:   []string{"*"},
            AllowCredentials: true,
    
            AllowedHeaders: []string{"Authorization", "Content-Type", "Access-Control-Allow-Origin"},
            // Enable Debugging for testing, consider disabling in production
            AllowedMethods: []string{"GET", "UPDATE", "PUT", "POST", "DELETE"},
            Debug:          true,
        })
    

    【讨论】:

    • 没有帮助(它没有帮助(前面部分仍然给出错误СORS。
    • 是的,同样的错误。邮递员不处理 CORS,因此所有请求都完美地通过它。
    【解决方案2】:

    你如何测试这个?当浏览器必须发出未通过飞行前条件的跨域请求时,将发送OPTIONS 请求。此OPTIONS 请求包含一个标头,其值为跨域请求中使用的 HTTP 方法。

    我建立了你的服务器的简化版本,这里有一些 curl 命令和结果示例。

    以下请求工作正常,我已将 Access-Control-Request-Method 设置为 GET

    curl -I -X OPTIONS -H "Origin: test.com" -H "Access-Control-Request-Method: GET" http://localhost:8080/
    HTTP/1.1 200 OK
    Access-Control-Allow-Credentials: true
    Access-Control-Allow-Methods: GET
    Access-Control-Allow-Origin: *
    Vary: Origin
    Vary: Access-Control-Request-Method
    Vary: Access-Control-Request-Headers
    Date: Tue, 11 Jun 2019 02:20:35 GMT
    Content-Length: 0
    

    如果没有 Access-Control-Request-Method 标头,以下请求将无法工作。我们的服务器可能对GETPOST (等等)有不同的CORS 设置,我们的服务器无法与客户端进行通信。客户端必须设置Access-Control-Request-Method 标头,以便服务器知道如何正确响应。

    curl -I -X OPTIONS -H "Origin: test.com" http://localhost:8080/
    HTTP/1.1 200 OK
    Date: Tue, 11 Jun 2019 02:31:12 GMT
    Content-Length: 436
    Content-Type: text/html; charset=utf-8
    

    【讨论】:

    • 感谢您的回答。这是我从前面发送的标题:Access-Control-Request-Headers: authorization,content-type Access-Control-Request-Method: GET Origin: http://localhost:3000 Referer: http://localhost:3000/patients User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36
    • 另外,你的 Docker 配置是什么样的?您的服务器在容器内监听哪个端口?哪些端口会暴露在 Internet 上?您是否在容器内使用了 Nginx 或 Apache 之类的代理?
    • 这是我的 docekr-compose 文件version: '3.3' services: api: container_name: 'api' build: './api' ports: - '8080:8080' volumes: - './api:/go/src/app' network_mode: host
    • 我不使用 Apache 和 Nginx
    • 你能运行相同的 curl 命令吗(调整为适当的 IP 地址)?或者用 Postman 模拟 OPTIONS/GET 请求。
    猜你喜欢
    • 2019-04-10
    • 2021-09-19
    • 2017-10-27
    • 2016-02-15
    • 2015-09-25
    • 2017-11-09
    • 2015-12-03
    • 2020-03-30
    相关资源
    最近更新 更多