我正在使用JavaScript前端和后端。我使用go gin框架创建了一个API。
我的main.go是:
func main() {
router := gin.Default()
router.GET("/", getBasicBlogInfo)
router.Use(cors.Default())
err := router.Run("localhost:8080")
if err != nil {
log.Fatalln("Unable to run the server.")
}
}现在在我的index.js
fetch('localhost:8080')
.then(response => response.json())
.then(data => console.log(data))
.catch((error) => {
console.error('Error:', error);
});然而,我得到一个CORS-起源请求块错误。
我得到的错误是:
Error: TypeError: NetworkError when attempting to fetch resource.CORS之一是:
跨源请求被阻止:相同的原产地策略不允许在http://localhost:8080/上读取远程资源。(原因: CORS标题“访问-控制-允许-起源”丢失)。状态代码: 200.
发布于 2022-05-02 12:29:17
import "github.com/gin-contrib/cors"
// r.Use(AllowAll())
func AllowAll() gin.HandlerFunc{
cfg := cors.Config{
AllowMethods: []string{"*"},
AllowHeaders: []string{"*"},
AllowCredentials: true,
MaxAge: 12 * time.Hour,
}
cfg.AllowAllOrigins = true
return cors.New(cfg)
}https://stackoverflow.com/questions/72086521
复制相似问题