我正在使用 Golang 和 Angular 18 构建一个全栈项目。我遇到了 CORS 问题。当我尝试从前端访问
http://localhost:8080/api/v1/auth/login
(POST) 时,没有 CORS 错误。但是,当我尝试访问 http://localhost:8080/api/v1/todos
(GET) 时,遇到 CORS 错误 (for /todos/*) 。谁能解释为什么会发生这种情况以及如何解决它?
这是我尝试访问
http://localhost:8080/api/v1/todos
(GET)时出现的错误:
Access to XMLHttpRequest at 'http://localhost:8080/api/v1/todos' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
这是我的main.go。
package main
import (
"github.com/JahidNishat/DailyPractice/todo-app/todo-backend/internal/auth"
"github.com/JahidNishat/DailyPractice/todo-app/todo-backend/internal/database"
"github.com/JahidNishat/DailyPractice/todo-app/todo-backend/internal/todo"
"github.com/JahidNishat/DailyPractice/todo-app/todo-backend/internal/user"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
"log"
)
func main() {
database.LoadConfig()
database.ConnectDB()
log.Println("Database Connected Successfully")
router := gin.Default()
router.Use(cors.Default())
router.Use(gin.Logger())
router.Use(gin.Recovery())
apiGroup := router.Group("/api/v1")
userApi := user.NewUserController()
todoApi := todo.NewTodoController()
authApi := auth.NewAuthController()
userApi.Router(apiGroup)
authApi.Router(apiGroup)
todoApi.Router(apiGroup)
port := viper.GetString("port")
if port == "" {
port = "8080"
}
if err := router.Run(":" + port); err != nil {
log.Fatal(err)
}
}
这是我的待办事项包。
package todo
import (
"github.com/JahidNishat/DailyPractice/todo-app/todo-backend/internal/middleware"
"github.com/JahidNishat/DailyPractice/todo-app/todo-backend/internal/repository"
"github.com/gin-gonic/gin"
)
type TodoHandler struct {
TodoStore repository.TodoRepos
UserStore repository.UserRepos
}
func NewTodoController() TodoHandler {
t := repository.NewTodoRepos()
u := repository.NewUserRepos()
return TodoHandler{
TodoStore: t,
UserStore: u,
}
}
func (t *TodoHandler) Router(router *gin.RouterGroup) {
todo := router.Group("/todos")
todo.Use(middleware.AuthMiddleware())
todo.POST("/", t.CreateTodo)
todo.GET("/", t.ListTodo)
todo.GET("/:id", t.GetTodo)
todo.PUT("/:id", t.UpdateTodo)
todo.DELETE("/:id", t.DeleteTodo)
}
这是我的授权包。
package auth
import (
"github.com/JahidNishat/DailyPractice/todo-app/todo-backend/internal/repository"
"github.com/gin-gonic/gin"
)
type AuthHandler struct {
UserStore repository.UserRepos
}
func NewAuthController() AuthHandler {
u := repository.NewUserRepos()
return AuthHandler{
UserStore: u,
}
}
func (a *AuthHandler) Router(router *gin.RouterGroup) {
auth := router.Group("/auth")
auth.POST("/login", a.LogIn)
auth.POST("/register", a.Register)
}
我尝试过
github.com/gin-contrib/cors
pkg。使用router.Use(cors.Default())
。还使用:
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}
router.Use(CORSMiddleware())
但是它并没有解决cors错误。
您的 Angular 应用程序使用代理配置吗?
例如:
const PROXY_CONFIG = [
{
context: ['/api-shift'],
target: "http://localhost:9098/shift-service",
changeOrigin: true,
secure: false,
// pathRewrite: {'^/api-shift': ''},
logLevel: 'debug',
},
];
module.exports = PROXY_CONFIG;
当我使用 Angular 应用程序时,我遇到了同样的错误,但这个文件为我解决了这个问题。