vue.js之从源地址访问 XMLHttpRequest 已被 CORS 策略阻止

kerrycode 阅读:156 2025-06-02 22:19:02 评论:0

在过去的 3 天里,我一直试图弄清楚为什么这不起作用,当我从 Vue Axios API 调用向后端发送请求时,我在下面收到一个 CORS 策略错误。
我的应用程序堆栈:

  • 戈朗( Gin )
  • 视频
  • PostgreSQL (戈姆)

  • 我在浏览器中收到错误:
    Access to XMLHttpRequest at 'http://localhost:8000/admin/users' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. 
    
    我尝试使用 'Access-Control-Allow-Origin': 'http://localhost:8080' 设置标题在 Vue 方面和 Gin 方面有许多不同的变化:
    Vue
     const apiClient = axios.create({ 
     baseURL: baseURL, 
     withCredentials: false, // This is the default 
     crossDomain: true, 
     headers: { 
      'Accept': 'application/json', 
      'Content-Type': 'application/json', 
      'Access-Control-Allow-Origin': 'http://localhost:8080' 
      // 'Accept-Encoding': 'gzip, deflate, br' 
     }, 
     timeout: 10000 
     }) 
    
    Gin :
    r := gin.Default() 
     
    //config := cors.DefaultConfig() 
    //config.AllowOrigins = []string{"http://localhost:8000"} 
    //r.Use(cors.New(config)) 
     
    r.Use(cors.Default()) 
    
    但是没有任何效果,这一切都始于我必须设置 withCredentials: true 因为我需要将视野发送到后端。
    我开始认为可能是因为此用户路由位于私有(private)组或其他东西中,但我对此表示怀疑:
    // User routes 
    admin := r.Group("/admin") 
    admin.Use(controllers.AuthRequired) 
    { 
        admin.GET("/users/", controllers.FindUsers) 
        admin.GET("/users/:id", controllers.FindUser) 
        admin.POST("/users", controllers.CreateUser) 
        admin.PATCH("/users/:id", controllers.UpdateUser) 
        admin.DELETE("/users/:id", controllers.DeleteUser) 
    } 
    
    谁能给我一些我可以尝试的其他想法。

    请您参考如下方法:

    你试过 github.com/rs/cors 吗?
    我认为您可以在 golang 上使用它:
    https://github.com/rs/cors/blob/master/examples/gin/server.go
    例子 :

      import ( 
        "github.com/gin-gonic/gin" 
        cors "github.com/rs/cors/wrapper/gin" 
    ) 
     
    func SetupRouter() *gin.Engine { 
        r := gin.Default() 
        r.Use(cors.AllowAll()) 
        r.GET("/ping", func(c *gin.Context) { 
            c.String(200, "pong") 
        }) 
        return r 
    } 
    
    如果您使用 r.Use(cors.Default()) 您只需打开 GET 和 POST 方法
    希望可以帮助..


    标签:VUE
    声明

    1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

    关注我们

    一个IT知识分享的公众号