gpt4 book ai didi

go - 如何解决 "No ' Access-Control-Allow-Origin' header is present on the requested resource”

转载 作者:IT王子 更新时间:2023-10-29 01:46:47 26 4
gpt4 key购买 nike

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

我现在在做什么:

Go 服务器代码:

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

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

Access to XMLHttpRequest at 'http://ip:8080/config' from origin 'http://ip:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我还尝试了以下代码来检查 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")

最佳答案

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)
}

关于go - 如何解决 "No ' Access-Control-Allow-Origin' header is present on the requested resource”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53985247/

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