我设置了一个中间件和路由器来处理路径/api/on
上的AJAX请求,就像这样
http.HandleFunc("/",route.IndexHandler)
http.HandleFunc("/login",route.GoogleLoginHandler)
http.HandleFunc("/auth/google",route.GoogleCallbackHandler)
http.Handle("/dashboard",negroni.New(
negroni.HandlerFunc(route.IsAuthenticated),
negroni.Wrap(http.HandlerFunc(route.DashboardHandler)),
))
http.Handle("/api/on",negroni.New(
negroni.HandlerFunc(route.IsAuthenticated),
negroni.Wrap(http.HandlerFunc(route.TurnOn)),
))
如果我的网络中有用户会话,中间件IsAuthenticated
允许跳转到下一个路由器,否则会重定向
func IsAuthenticated(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
session, _ := util.GlobalSessions.SessionStart(w, r)
defer session.SessionRelease(w)
if session.Get("profile") == nil {
http.Redirect(w, r, "/", http.StatusMovedPermanently)
} else {
next(w, r)
}
}
这是后续流程的TurnOn
处理程序
func TurnOn(w http.ResponseWriter, r *http.Request) {
session, _ := util.GlobalSessions.SessionStart(w, r)
defer session.SessionRelease(w)
w.Header().Set("Access-Control-Allow-Origin","*")
w.Header().Set("Access-Control-Allow-Methods","POST")
w.Header().Set("Access-Control-Allow-Headers","Content-Type")
fmt.Println(r.URL)
}
打开服务器后,我使用AJAX使用JavaScript的客户端代码执行了POST请求,但控制台没有记录任何内容。即使成功发送AJAX请求,似乎仍未达到TurnOn
函数。我明显错过了什么吗?