如何解决“请求的资源上不存在“ Access-Control-Allow-Origin”标头”

时间:2018-12-31 08:30:59

标签: go

我正在Go中实现REST API,为此,我希望允许处理跨源请求。

我目前正在做什么:

转到服务器代码:

//handleCrossO ... This function will handle CROS
func handleCrossO(w *http.ResponseWriter) {
(*w).Header().Set("Content-Type", "application/json")
(*w).Header().Set("Access-Control-Allow-Origin", "*")
(*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, 
     OPTIONS, PUT, DELETE")
(*w).Header().Set("Access-Control-Allow-Headers", "Accept, 
     Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, 
     Authorization, Auth")
}

//Response ... This function will create response
func Response(w http.ResponseWriter, message string, statusCode int) 
{
handleCrossO(&w)
w.WriteHeader(statusCode)
w.Write([]byte("{\"message\":\"" + message + "\"}"))
}

我在浏览器控制台上遇到以下错误:

  

从原点“ http://ip:8080/config”到“ http://ip:4200”处对XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:否'Access-Control-Allow-来源的标头出现在请求的资源上。

我还尝试了以下代码来检查OPTIONS方法:

// CheckAuthorization function check if the User is autrhorized to make calls or not
// if ssid is mising then give unauthorized error otherwise call next
func CheckAuthorization(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
    if r.Method == "OPTIONS" {
        //handle preflight in here
        response.Response(w, "success", 200)
    }else {
            store := session.SessionStore()
        session, _ := store.Get(r, utils.SessionName)
        ssid := r.Header.Get("Auth")
        if _, ok := session.Values[ssid]; ok {
            next.ServeHTTP(w, r)
        } else {
        var getTokenRes = GetTokenRes{}
        sendResponse(w, getTokenRes, 1, "Invalid 
                     SSID", 400)
        }
    }

}
}

但是它不起作用。

我还尝试了允许OPTIONS方法:

router.HandleFunc("/network", authmiddleware.CheckAuthorization(createConfiguration)).Methods("POST", "OPTIONS")

1 个答案:

答案 0 :(得分:0)

Preflight request应该返回成功和标题。尝试像下面这样使用

func setupResponse(w *http.ResponseWriter, req *http.Request) {
    (*w).Header().Set("Access-Control-Allow-Origin", "*")
    (*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
    (*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}

func indexHandler(w http.ResponseWriter, req *http.Request) {
    setupResponse(&w, req)
    if (*req).Method == "OPTIONS" {
        return
    }

    // process the request...
}

您还可以使用https://github.com/rs/cors

package main

import (
    "net/http"

    "github.com/rs/cors"
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        w.Write([]byte("{\"hello\": \"world\"}"))
    })

    // cors.Default() setup the middleware with default options being
    // all origins accepted with simple methods (GET, POST). See
    // documentation below for more options.
    handler := cors.Default().Handler(mux)
    http.ListenAndServe(":8080", handler)
}