我在这里有相当简单的设置,如下面的代码所述。但我无法得到CORS
上班。我不断收到此错误:
XMLHttpRequest 无法加载http://localhost:3000/signup http://localhost:3000/signup。响应
预检请求未通过访问控制检查:无“访问-”
Control-Allow-Origin'标头存在于所请求的资源上。
起源 'http://本地主机:8000 http://localhost:8000' 因此不允许访问。这
响应的 HTTP 状态代码为 403。
我确信我在这里缺少一些简单的东西。
这是我的代码:
package main
import (
"log"
"net/http"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"myApp/src/controllers"
)
func main() {
ac := new(controllers.AccountController)
router := mux.NewRouter()
router.HandleFunc("/signup", ac.SignUp).Methods("POST")
router.HandleFunc("/signin", ac.SignIn).Methods("POST")
log.Fatal(http.ListenAndServe(":3000", handlers.CORS()(router)))
}
请阅读 Markus 建议的链接,以及有关触发 CORS 飞行前请求的内容的信息。
飞行前请求:您可能有一个内容类型(例如 JSON)或其他一些触发飞行前请求的自定义标头,而您的服务器可能无法处理这些请求。如果您在前端使用常见的 AJAX,请尝试添加此一项:https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Requested-With https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Requested-With
大猩猩的handlers.CORS()
将设置合理的默认值,让 CORS 的基础知识为您工作;但是,您可以(也许应该)以更实用的方式进行控制。
这是一些起始代码:
// Where ORIGIN_ALLOWED is like `scheme://dns[:port]`, or `*` (insecure)
headersOk := handlers.AllowedHeaders([]string{"X-Requested-With"})
originsOk := handlers.AllowedOrigins([]string{os.Getenv("ORIGIN_ALLOWED")})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
// start server listen
// with error handling
log.Fatal(http.ListenAndServe(":" + os.Getenv("PORT"), handlers.CORS(originsOk, headersOk, methodsOk)(router)))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)