Skip to content

Commit 18d2cc6

Browse files
committed
fix: router cors error
1 parent 6c2a8be commit 18d2cc6

1 file changed

Lines changed: 21 additions & 1 deletion

File tree

pkg/router/router.go

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"mkBlog/config"
55
"mkBlog/pkg/cache"
66
"mkBlog/pkg/middleware"
7+
"net/http"
78
"os"
89
"path/filepath"
910
"strings"
@@ -17,10 +18,29 @@ func GetRouter() *gin.Engine {
1718
return r
1819
}
1920

21+
func CORSMiddleware() gin.HandlerFunc {
22+
return func(c *gin.Context) {
23+
// 如果你只想允许自己域名,把 * 换成具体域名
24+
// 例如:https://mkitsdts.top
25+
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
26+
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
27+
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
28+
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
29+
30+
// 处理预检请求,直接返回 200
31+
if c.Request.Method == http.MethodOptions {
32+
c.AbortWithStatus(http.StatusOK)
33+
return
34+
}
35+
36+
c.Next()
37+
}
38+
}
39+
2040
func InitRouter() error {
2141
gin.SetMode(gin.ReleaseMode)
2242
r = gin.New()
23-
r.Use(gin.Logger(), gin.Recovery())
43+
r.Use(gin.Logger(), gin.Recovery(), CORSMiddleware())
2444
// 启用黑名单
2545
r.Use(middleware.Blacklist())
2646

0 commit comments

Comments
 (0)