AngularJS页面无法从服务器刷新。

huangapple go评论72阅读模式
英文:

AngularJS page does not refresh from server

问题

我有一个AngularJS应用程序。服务器端是Go,并使用Gorilla Web Toolkit mux和sessions包。Angular应用程序在主页上有两个表单,登录和注册。数据以JSON格式通过AngularJS的$http.post方法发送到Go,并从服务器返回适当的JSON响应。我想要实现的是,根据用户是否已登录,在网站的主页上提供两个不同的页面。目前,当我提交登录表单的详细信息并且服务器以适当的响应进行响应时,我重新加载页面,但是AngularJS仍然显示带有表单的页面,而不是新页面。

AngularJS代码

angular.module('app', [])

angular.module('app').controller('SignInController', ['$scope', '$http', function($scope, $http) {
    $scope.formData = {}

    $scope.signIn = function() {
        $http.post('/signIn', {
            email: $scope.formData.email,
            password: $scope.formData.password
        }).success(function(data) {
            console.log(data)
            if(data.ok == true) {
                window.location.reload(true)
            }
        })
    }
}])

相关的Go代码
下面的代码中,当向"/signIn"发起POST请求时,SignInHandler被调用,当向"/"发起GET请求时,IndexHandler被调用。

type JsonResponse map[string]interface{}

func (jr JsonResponse) String() (output string) {
    b, err := json.Marshal(jr)
    if err != nil {
        output = ""
        return
    }
    output = string(b)
    return
}

func SignInHandler(w http.ResponseWriter, r *http.Request) {
    session, _ := sessionStore.Get(r, "user-session")

    decoder := json.NewDecoder(r.Body)
    var user User
    err := decoder.Decode(&user)
    if err != nil {
        fmt.Fprint(w, JsonResponse{"ok": false, "message": "Bad request"})
        return
    }

    if user.Email == "" || user.Password == "" {
        fmt.Fprint(w, JsonResponse{"ok": false, "message": "All fields are required"})
        return
    }

    userExists, u := user.Exists()
    if userExists == false {
        fmt.Fprint(w, JsonResponse{"ok": false, "message": "Email and/or password in invalid"})
        return
    }

    err = bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(user.Password))
    if err != nil {
        fmt.Fprint(w, JsonResponse{"ok": false, "message": "Email and/or password in invalid"})
        return
    }

    session.Values["userId"] = u.Id.Hex()

    session.Save(r, w)

    fmt.Fprint(w, JsonResponse{"ok": true, "message": "Authentication Successful"})
}

func IndexHandler(w http.ResponseWriter, r *http.Request) {
    session, _ := sessionStore.Get(r, "promandi-user-session")

    if _, ok := session.Values["userId"]; ok {
        http.ServeFile(w, r, "./views/home.html")
    } else {
        http.ServeFile(w, r, "./views/index.html")
    }
}
英文:

I have an AngularJS app. The server side is Go and uses Gorilla Web Toolkit mux and sessions packages. The Angular app has two forms on the main page, Sign In and Sign Up. The data is posted to Go using AngularJS $http.post as JSON and appropriate responses are sent back from the server as JSON. What I want to achieve is that two different pages should be served on the main page of the website depending on if the user is logged in or not. Currently, when I submit the details of the Sign In form and the server responds with an appropriate response, I reload the page, but AngularJS keeps showing the page with the forms and not the new page.

AngularJS Code

angular.module('app', [])
angular.module('app').controller('SignInController', ['$scope', '$http', function($scope, $http) {
$scope.formData = {}
$scope.signIn = function() {
$http.post('/signIn', {
email: $scope.formData.email,
password: $scope.formData.password
}).success(function(data) {
console.log(data)
if(data.ok == true) {
window.location.reload(true)
}
})
}
}])

Relevant Go Code
Below, the SignInHandler gets called on a POST to "/signIn" and the IndexHandler gets called on a Get to "/".

type JsonResponse map[string]interface{}
func (jr JsonResponse) String() (output string) {
b, err := json.Marshal(jr)
if err != nil {
output = ""
return
}
output = string(b)
return
}
func SignInHandler(w http.ResponseWriter, r *http.Request) {
session, _ := sessionStore.Get(r, "user-session")
decoder := json.NewDecoder(r.Body)
var user User
err := decoder.Decode(&user)
if err != nil {
fmt.Fprint(w, JsonResponse{"ok": false, "message": "Bad request"})
return
}
if user.Email == "" || user.Password == "" {
fmt.Fprint(w, JsonResponse{"ok": false, "message": "All fields are required"})
return
}
userExists, u := user.Exists()
if userExists == false {
fmt.Fprint(w, JsonResponse{"ok": false, "message": "Email and/or password in invalid"})
return
}
err = bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(user.Password))
if err != nil {
fmt.Fprint(w, JsonResponse{"ok": false, "message": "Email and/or password in invalid"})
return
}
session.Values["userId"] = u.Id.Hex()
session.Save(r, w)
fmt.Fprint(w, JsonResponse{"ok": true, "message": "Authentication Successful"})
}
func IndexHandler(w http.ResponseWriter, r *http.Request) {
session, _ := sessionStore.Get(r, "promandi-user-session")
if _, ok := session.Values["userId"]; ok {
http.ServeFile(w, r, "./views/home.html")
} else {
http.ServeFile(w, r, "./views/index.html")
}
}

答案1

得分: 1

在我添加了"Cache-Control": "no-store"头部到我的IndexHandler之后,它开始正常运行。

w.Header().Set("Cache-Control", "no-store")

英文:

It started behaving properly after I added the "Cache-Control": "no-store" header in my IndexHandler.

w.Header().Set("Cache-Control", "no-store")

huangapple
  • 本文由 发表于 2015年5月9日 14:29:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/30136801.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定