我遇到了在开发环境中实现跨源资源共享的问题,在反应性前端和Go-lang Gin-Gonic框架之间,下面是浏览器的控制台日志。


来自react应用程序发送post请求的控制台日志
这是从Go框架接收到的请求,可以看到,未验证飞行前请求。
我曾尝试过两次黑客攻击,一次是验证飞行前请求,然后在以下反应选项上传递200次。
func preflight(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Headers", "access-control-allow-origin, access-control-allow-headers")
c.JSON(http.StatusOK, struct{}{})
}这个黑客没有帮助,此外,我还在访问控制允许原点中包括了一个带有通配符域的中间件,以及http://localhost:3000,如下所示
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Credentials", "true")
c.Header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Header("Access-Control-Allow-Methods", "POST,HEAD,PATCH, OPTIONS, GET, PUT")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}我还尝试了gin cors包,如下面所示:github.com/gin-cont肋骨/cors,但是请求仍然被阻止。

These are part of my routes
r := gin.Default()
//r := gin.New()
config := cors.DefaultConfig()
config.AllowOrigins = []string{"*"}
// config.AllowOrigins = []string{"http://google.com", "http://facebook.com"}
// config.AllowAllOrigins = true
r.Use(cors.New(config))
//system routes
router.NotFound(r)
router.NoMethods(r)
//static routes
router.ServeStatic(r)
Methods
func NotFound(route *gin.Engine) {
route.NoRoute(func(c *gin.Context) {
c.JSON(404, gin.H{"msg": "Not Found"})
})
}
func NoMethods(route *gin.Engine) {
route.NoMethod(func(c *gin.Context) {
c.JSON(405, gin.H{"msg": "Not allowed"})
})
}
//Serve frontend static files
func ServeStatic(route *gin.Engine) {
route.Use(static.Serve("/", static.LocalFile("./views/public", true)))
route.Use(auth.CORSMiddleware())
api := route.Group("/api")
{
api.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
}go版本是go版本go1.18.1 linux/amd64 64
"axios": "^0.24.0",
"react": "^18.1.0",发布于 2022-05-11 23:50:33
尝试在handleFunc之前移动CORS中间件
示例:
func (h *Handler) InitRoutes() *gin.Engine {
router := gin.New()
router.Use(h.setHeaders)
router.GET("/", h.getRecordsByFilter)
router.GET("/:uuid", h.getRecordByUuid)
router.POST("/", h.createRecord)
router.PUT("/:uuid", h.updateRecord)
router.DELETE("/:uuid", h.deleteRecord)
return router
}发布于 2022-05-20 03:47:10
问题是来自反应前端的凭证是真实的。
handleSubmit(event) {
const {email,password} = this.state;
axios.post("http://localhost:3000/auth/register",
{email: email, password: password},{
withCredentials: true}).then(response => {
console.log("registration res", response);
console.log("response data",response.data);
}).catch(error => {
console.log("registratino error", error);
});
event.preventDefault();
}https://stackoverflow.com/questions/72181878
复制相似问题