我用 Golang 的Gin 框架和JWT 中間件構建了一個后端。這是我使用的自述文件中的官方示例:main.gopackage mainimport ( "log" "net/http" "os" "time" "github.com/appleboy/gin-jwt/v2" "github.com/gin-gonic/gin")type login struct { Username string `form:"username" json:"username" binding:"required"` Password string `form:"password" json:"password" binding:"required"`}var identityKey = "id"func helloHandler(c *gin.Context) { claims := jwt.ExtractClaims(c) user, _ := c.Get(identityKey) c.JSON(200, gin.H{ "userID": claims[identityKey], "userName": user.(*User).UserName, "text": "Hello World.", })}// User demotype User struct { UserName string FirstName string LastName string}func main() { port := os.Getenv("PORT") r := gin.New() r.Use(gin.Logger()) r.Use(gin.Recovery()) if port == "" { port = "8000" } // the jwt middleware authMiddleware, err := jwt.New(&jwt.GinJWTMiddleware{ Realm: "test zone", Key: []byte("secret key"), Timeout: time.Hour, MaxRefresh: time.Hour, IdentityKey: identityKey, PayloadFunc: func(data interface{}) jwt.MapClaims { if v, ok := data.(*User); ok { return jwt.MapClaims{ identityKey: v.UserName, } } return jwt.MapClaims{} }, IdentityHandler: func(c *gin.Context) interface{} { claims := jwt.ExtractClaims(c) return &User{ UserName: claims[identityKey].(string), }我 Angular 8 中的身份驗證服務如下所示:但這在 Chrome 中給了我一條錯誤消息:Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.不過,在控制臺中,Gin 返回狀態(tài)碼 204。我重新啟動了ng serve,但仍然出現(xiàn)錯誤(我根據(jù)代理文件中的配置將auth.service和main.go中的url改為/api/login)。我在這里做錯了什么?
- 1 回答
- 0 關注
- 174 瀏覽
添加回答
舉報
0/150
提交
取消