登录
首页 >  Golang >  Go问答

GoLang和Vue项目中解决跨域(CORSE)问题

来源:stackoverflow

时间:2024-02-19 20:09:24 304浏览 收藏

一分耕耘,一分收获!既然都打开这篇《GoLang和Vue项目中解决跨域(CORSE)问题》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!

问题内容

我和我的团队正在开发一个项目,该项目在后端使用 golang,以 gin、gorm、jwt、加密框架和 vue 作为前端。我们使用 jwt 创建了一个令牌验证系统。这是我们的用户控制器文件内容,其中包含登录、登录和验证方法:

package controllers



type bodys struct {
    username string
    mail     string
    password string
    dropdown int
}
type bodyl struct {
    mail     string
    password string
}

func signup(c *gin.context) {
    var body bodys
    var mentor models.mentor
    var company models.company

    if c.bindjson(&body) != nil {
        c.json(http.statusbadrequest, gin.h{
            "error": "data err",
        })
        return
    }

    hash, err := bcrypt.generatefrompassword([]byte(body.password), 10)

    if err != nil {
        c.json(http.statusbadrequest, gin.h{
            "error": "password err",
        })
        return
    }

    var user models.user

    user.mail = body.mail
    user.password = string(hash)
    user.username = body.username
    res := config.db.create(&user)

    if res.error != nil {
        c.json(http.statusbadrequest, gin.h{
            "error": "user err",
        })
        return
    }

    if body.dropdown == 1 {
        mentor.userid = user.id
        //mentor.isindividual = true
        mentor.companyid = 3
        config.db.create(&mentor)
        c.json(202, mentor)
        c.redirect(http.statusfound, "/mentorpage")

    }
    if body.dropdown == 2 {
        company.userid = user.id
        config.db.create(&company)
        c.json(202, "şirket olarak kaydınız yapıldı")
        c.redirect(http.statusfound, "/companypage")

    }
    c.json(http.statusok, gin.h{})
}

func login(c *gin.context) {
    //enablecors(&w)
    var body bodyl
    var rol string
    var mentor models.mentor
    var mentee models.mentee
    var company models.company
    if c.bind(&body) != nil {
        c.json(http.statusbadrequest, gin.h{
            "error": "data err",
        })
        return
    }

    var user models.user
    config.db.first(&user, "mail = ?", body.mail)
    fmt.println(user.mail)
    if user.id == 0 {
        c.json(http.statusbadrequest, gin.h{
            "error": "user err",
        })
        return
    }
    erro := bcrypt.comparehashandpassword([]byte(user.password), []byte(body.password))

    if erro != nil {
        c.json(http.statusbadrequest, gin.h{
            "error": "password err",
        })
        return
    }
    config.db.first(&mentor, "user_id = ?", user.id)
    config.db.first(&mentee, "user_id = ?", user.id)
    config.db.first(&company, "user_id = ?", user.id)

    if mentor.id != 0 {
        rol = "mentor"
    }
    if mentee.id != 0 {
        rol = "mentee"
    }
    if company.id != 0 {
        rol = "company"
    }
    if mentor.id == 0 && mentee.id == 0 && company.id == 0 {
        rol = "user"
    }

    token := jwt.newwithclaims(jwt.signingmethodhs256, jwt.mapclaims{
        "sub":  user.id,
        "rol":  rol,
        "mail": user.mail,
        "exp":  time.now().add(time.hour * 24).unix(),
    })
    tokenstring, err := token.signedstring([]byte(os.getenv("secret")))
    fmt.println(tokenstring)
    if err != nil {
        c.json(http.statusbadrequest, gin.h{
            "error": "token err",
        })
        return
    }
    c.setsamesite(http.samesitelaxmode)
    c.setcookie("authorization", tokenstring, 3600*24, "", "", false, true)
    c.json(http.statusok, gin.h{
        "token": tokenstring,
    })

}

func validate(c *gin.context) {
    user, _ := c.get("user")
    //un := user.(models.user).username
    c.json(http.statusok, gin.h{
        "data": user,
    })
}

我们正在使用中间件:

func requireauth(c *gin.context) {
    tokenstring, err := c.cookie("authorization")

    if err != nil {
        fmt.println("error1")
        c.abortwithstatus(http.statusunauthorized)
    }

    token, _ := jwt.parse(tokenstring, func(token *jwt.token) (interface{}, error) {
        if _, ok := token.method.(*jwt.signingmethodhmac); !ok {
            return nil, fmt.errorf("poşet giriş beklenmemişti: %v", token.header["alg"])
        }
        return []byte(os.getenv("secret")), nil
    })
    if claims, ok := token.claims.(jwt.mapclaims); ok && token.valid {
        if float64(time.now().unix()) > claims["exp"].(float64) {
            fmt.println("error3")
            c.abortwithstatus(http.statusunauthorized)
        }
        var user models.user
        config.db.first(&user, claims["sub"])
        if user.id == 0 {
            fmt.println("error2")
            c.abortwithstatus(http.statusunauthorized)
        }
        c.set("user", user)
        c.next()

    } else {
        fmt.println("error4")
        c.abortwithstatus(http.statusunauthorized)
    }

}

这些是我们的路线:

func userroute(router *gin.engine) {
   router.post("/signup", controllers.signup)
   router.post("/login", controllers.login)
   router.get("/validate", middleware.requireauth, controllers.validate)
   router.post("/logout", controllers.logout)

}

我们在 main 中这样称呼我们的路由:

func main() {
    router := gin.Default()

    Config.Connect()
    Routes.UserRoute(router)
    router.Run(":8080")

}

当我们通过单击登录按钮从前端部分调用登录方法时,如下所示:

我们采取了如下图所示的错误:

输出如下:

我们如何管理这个 cors 错误。我们需要帮助。感谢您抽出时间。


正确答案


您需要一个 CORS 中间件,它处理 OPTIONS 请求并向响应添加适当的 Access-Control-Allow-Methods 标题,这基本上告诉浏览器服务器允许接受来自另一个域的请求。

总的来说,它是一个很好的工具,可以控制谁可以向您的服务器发送请求、该请求可能是什么以及具体来自何处。

您可以使用 https://github.com/gin-contrib/cors 之类的东西,或者只是编写自己的中间件,实际上代码并不多。

还值得一提的是,如果您的前台位于 example.com 并且您的 api 也位于那里,例如:example.com/api – 您将不需要在产品上进行任何 CORS 配置。

好了,本文到此结束,带大家了解了《GoLang和Vue项目中解决跨域(CORSE)问题》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>