POST 请求在 beego 框架上被视为选项

POST request treated as OPTIONS on beego framework

我将 beego 框架用作我的 API 框架,并在客户端上使用 AngularJS。 我已正确设置所有 CORS 设置。我可以做 GET 请求。但是,当我尝试 POST 时,beego treat 是作为 OPTIONS 请求。它还会发出警告:multiple response.WriteHeader calls。可能有什么问题?

我的 beego CORS 设置:

func init() {
    orm.RegisterDataBase("default", "mysql", "root:@tcp(127.0.0.1:3306)/fakeapi")
    beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
        AllowOrigins:     []string{"*"},
        AllowMethods:     []string{"GET", "DELETE", "PUT", "PATCH", "POST"},
        AllowHeaders:     []string{"Origin"},
        ExposeHeaders:    []string{"Content-Length"},
        AllowCredentials: true,
    }))

}

我的ANgularJS请求

var transaction = $http.post(BASE_URL + "transaction", transactionData);
                return $q.all([transaction]).then(function(response) {
            console.log(response);
        });

我的系统: Ubuntu 14.04 蜜蜂:1.4.2 蜜蜂:1.2.4 angularJS: 1.3.12

这可能是因为 issue/pull 请求当前正在等待合并到 master 中:issue 912

Without this line everything is fine:: router.go#L861

这似乎符合 commit 3bb4d6f 显示:

// Write status code if it has been set manually
// Set it to 0 afterwards to prevent "multiple response.WriteHeader calls"

(并且 router.go 确实设置了状态,因此出现了错误消息)

Commit f962457 应该可以解决这个问题,但还没有合并。


另一个 issue 904 提到无法检索先前在会话引擎中注册的会话数据。 也许 Session.on flag 可以提供帮助。

我就是这么处理的,希望对你有帮助

import (
_ "info_apoyo/routers"

"github.com/astaxie/beego"
"github.com/astaxie/beego/plugins/cors"
)

func main() {
if beego.BConfig.RunMode == "dev" {
    beego.BConfig.WebConfig.DirectoryIndex = true
    beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
}
beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
    AllowOrigins:     []string{"*"},
    AllowMethods:     []string{"GET", "POST", "DELETE", "PUT", "PATCH"},
    AllowHeaders:     []string{"Origin", "content-type", "Access-Control-
Allow-Origin"},
    ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-
Origin"},
    AllowCredentials: true,
}))
beego.Run()
}