3 回答
TA贡献1963条经验 获得超6个赞
这是我测试过的工作代码:
type Article struct {
ID int `json:"id"`
TITLE string `json:"title"`
CONTENT string `json:"content"`
}
var articles []Article
func main() {
db, err := sql.Open("mysql", "root:111111@tcp(localhost:3306)/article")
if err != nil {
panic(err.Error())
}
defer db.Close()
router := gin.Default()
router.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "OPTIONS"},
AllowHeaders: []string{"Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization", "accept", "origin", "Cache-Control", "X-Requested-With"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
AllowOriginFunc: func(origin string) bool {
return true
},
MaxAge: 15 * time.Second,
}))
api := router.Group("/api")
{
api.POST("/post", func(c *gin.Context) {
var article Article
c.BindJSON(&article)
ins, err := db.Prepare("INSERT INTO articles(title,content) VALUES(?,?)")
if err != nil {
log.Fatal(err)
}
ins.Exec(article.TITLE, article.CONTENT)
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
}
router.Run(":4000")
}
TA贡献1803条经验 获得超6个赞
正如错误所示,请求“已被 CORS 策略阻止”,CORS 策略是“跨域资源共享”的缩写,是浏览器实施的一项安全措施。解决方案是修改您的服务器以返回正确的“Access-Control-Allow-Origin”标头。
TA贡献1780条经验 获得超5个赞
在服务器端添加一些代码后,问题得到解决。
api.POST("/post", func(c *gin.Context) {
c.Header("Content-Type", "application/json")
c.Header("Access-Control-Allow-Origin", "*")
// add
c.Header("Access-Control-Allow-Headers", "Content-Type")
var article Article
c.BindJSON(&article)
ins, err := db.Prepare("INSERT INTO articles(title,content) VALUES(?,?)")
if err != nil {
log.Fatal(err)
}
ins.Exec(article.TITLE, article.CONTENT)
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
// add response to OPTIONS
api.OPTIONS("/post", func(c *gin.Context) {
c.Header("Content-Type", "application/json")
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Headers", "Content-Type")
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
- 3 回答
- 0 关注
- 241 浏览
添加回答
举报