Gorilla Mux Google Cloud端点CORS问题

时间:2018-01-26 17:12:12

标签: jquery go cors google-cloud-endpoints mux

我正在尝试使用gorilla mux和google cloud端点构建API,但我很难让它允许跨源请求。我在我的Web应用程序中使用以下代码发送请求:

jQuery(document).ready(function(){
  switchMsg();
  setInterval(switchMsg, 10000);
});

function switchMsg() {
    jQuery(".mszDivOuter").each(function(){
        var cnt = crActiveMsz = nextMszNum = 0; 
        cnt = $(this).children('.mszDiv').length;
        if(cnt > 1){
            crActiveMsz = $(this).children('.activeMsz').index();
            nextMszNum = crActiveMsz + 2;

            if(nextMszNum > cnt){ nextMszNum = 1;}

            $(this).children('.mszDiv').removeClass("activeMsz");
            $(this).children('.mszDiv').addClass("deactiveMsz");

            $(this).children('.mszDiv:nth-child('+nextMszNum+')').removeClass("deactiveMsz");
            $(this).children('.mszDiv:nth-child('+nextMszNum+')').addClass("activeMsz");
        }
    });
}

我在浏览器的控制台中收到以下错误:

$.ajax("https://my.api/echo", {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "Authorization": "Bearer " + localStorage.id_token
    },
    data: JSON.stringify({
        "message": this.query
    })
}).done(function(response) {
    console.log(response);
});

端点代码是:

OPTIONS https://my.api/echo 403 ()

Failed to load https://my.api/echo: Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin 
'http://127.0.0.1:8081' is therefore not allowed access. The response
had HTTP status code 403.

我的app.yaml是:

func main() {
    r := mux.NewRouter()

    r.HandleFunc("/echo", echoHandler).Methods("POST", "OPTIONS")
    headers := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type"})
    origins := handlers.AllowedOrigins([]string{"*"})
    methods := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})

    http.Handle("/", r)

    port := 10080
    if portStr := os.Getenv("PORT"); portStr != "" {
        port, _ = strconv.Atoi(portStr)
    }
    log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), handlers.CORS(headers, origins, methods)(r)))
}

func echoHandler(w http.ResponseWriter, r *http.Request) {
    // echoHandler reads a JSON object from the body, and writes it back out.
    var msg interface{}
    if err := json.NewDecoder(r.Body).Decode(&msg); err != nil {
        if _, ok := err.(*json.SyntaxError); ok {
            errorf(w, http.StatusBadRequest, "Body was not valid JSON: %v", err)
            return
        }
        errorf(w, http.StatusInternalServerError, "Could not get body: %v", err)
        return
    }

    b, err := json.Marshal(msg)
    if err != nil {
        errorf(w, http.StatusInternalServerError, "Could not marshal JSON: %v", err)
        return
    }
    w.Write(b)
}

1 个答案:

答案 0 :(得分:0)

您收到403错误,这意味着您的预检请求缺少通过访问控制检查的正确身份验证。

在这种情况下,请求所针对的资源的CORS配置应包含Access-Control-Allow-Origin标头。此标头应包含允许访问资源的所有HTTP源。

以防万一,您应该添加一个或多个Access-Control-Request-Header标头,其值必须与CORS配置中的ResponseHeader值匹配。 Access-Control-Request-Header中的所有标头都应出现在CORS配置的Access-Control-Allow-Origin标头中,以便可以授权请求。

您可以找到有关正确身份验证的更多信息here