我在Gin-Gonic中创建了一个带有Go的应用程序。在我的前端(Nuxt3/TypeScript)中,我总是得到一个CORS错误:
CORS策略已阻止从源“http://localhost:3000”访问“http://localhost:8081/api/v1/notion/database”:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果一个不透明的响应满足了你的需求,将请求的模式设置为“no-cors”,以在禁用CORS的情况下获取资源。
我注解掉了我的应用程序的所有端点,并一步一步地只构建了这两个端点。使用相同的CORS配置,端点突然工作。我构建了越来越多的端点,发现了以下错误:/api/v1/notion
端点工作正常,我可以访问它。/api/v1/notion/database
端点不工作并返回上述CORS错误。我使用Gin-Gonic的官方CORS middleware。
func main(){
r := gin.Default()
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"http://localhost:3000"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Authorization", "Origin", "Content-Type", "Accept"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
}))
r.GET("/api/v1/notion", func(c *gin.Context) {
c.JSON(http.StatusOK, "👋 OK")
})
r.GET("/api/v1/notion/database", func(c *gin.Context) {
c.JSON(http.StatusOK, "👋 OK")
})
r.Run(":8081")
}
我从前端发送的请求看起来像这样:
async function sendOwnRequest(){
const url1 = 'http://localhost:8081/api/v1/notion'
const url2 = 'http://localhost:8081/api/v1/notion/database'
const bearer = 'Bearer ey...'
const response = await window.fetch(url1, {
method: 'GET',
headers: {'Authorization': bearer},
mode: 'cors',
credentials: 'include',
})
const response = await window.fetch(url2, {
method: 'GET',
headers: {'Authorization': bearer},
mode: 'cors',
credentials: 'include',
})
}
你有什么想法的问题可能是,因为两者应该是100%相同的,除了URL路径。是否有必须设置的CORS属性?
版本号:
- go版本:
go1.20 darwin/arm64
- go list -m github.com/gin-gonic/gin:
v1.9.1
- go list -m github.com/gin-contrib/cors:
v1.4.0
- 节点--版本:
v18.17.0
- npm --version:
9.6.7
1条答案
按热度按时间tnkciper1#
服务器端代码
r.Run("8081")
应该是r.Run(":8081") // Note the colon before the port number
除此之外,我没有看到任何问题的代码,客户端代码也看起来很好
编辑:啊,我想你可能错过了浏览器的OPTIONS飞行前检查?就在打电话给
r.GET
之前