不说废话
在main函数前加入如下代码
func init() { //跨域设置 var FilterGateWay = func(ctx *context.Context) {ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*") //允许访问源 ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS") //允许post访问 ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers","Access-Control-Allow-Origin,ContentType,Authorization,accept,accept-encoding, authorization, content-type") //header的类型 ctx.ResponseWriter.Header().Set("Access-Control-Max-Age", "1728000") ctx.ResponseWriter.Header().Set("Access-Control-Allow-Credentials", "true") } beego.InsertFilter("*", beego.BeforeRouter, FilterGateWay) } //路由设置 ns := beego.NewNamespace("/v1", // 用于跨域请求 beego.NSRouter("*",&controllers.BaseController{},"OPTIONS:Options"),) beego.AddNamespace(ns)
定义option函数回应预检请求(controller中)
``` 定义option函数回应预检请求(controller中) ```go // @Title test // @Description 预检 // @Success 200 {string} "hello world" // @router / [options] func (c *BaseController) Options() { c.Data["json"] = map[string]interface{}{"status": 200, "message": "ok", "moreinfo": ""} c.ServeJSON() } ```
跨域请求是会先发送一个option请求,该请求如果收到响应(响应内容随便),客户端则才会继续发送请求
原文地址:https://www.cnblogs.com/qflyue/p/10295671.html
时间: 2024-10-10 21:38:15