0

AngularJS アプリがあります。サーバー側は Go で、Gorilla Web Toolkit の mux とセッション パッケージを使用します。Angular アプリのメイン ページには、サインインとサインアップの 2 つのフォームがあります。データは、AngularJS$http.postを JSON として使用して Go に送信され、適切な応答がサーバーから JSON として返されます。私が達成したいのは、ユーザーがログインしているかどうかに応じて、Web サイトのメイン ページに 2 つの異なるページを表示することです。現在、サインイン フォームの詳細を送信し、サーバーが適切な応答で応答すると、ページをリロードしますが、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 コード 以下では、SignInHandler が "/signIn" への POST で呼び出され、IndexHandler が "/" への Get で呼び出されます。

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")
    }
}
4

1 に答える 1

1

IndexHandler に "Cache-Control": "no-store" ヘッダーを追加すると、正しく動作するようになりました。

w.Header().Set("Cache-Control", "no-store")
于 2015-05-09T12:24:08.423 に答える