2016-05-23 56 views
0

我目前正在創建一個小應用程序,並遇到問題。我正在使用燒瓶jwt模塊,以便用戶檢索令牌以便能夠訪問暴露在python中的api。我正在使用angularjs來開發我的前端。當我嘗試登錄我的API根據文件駐留在返回400錯誤瓶jwt auth端點返回400

"POST /auth HTTP/1.1" 400 

服務器,所有我需要做的就是通過我的憑據,身份驗證端點和我應該能夠拿回令牌作爲展示在頁面上:https://pythonhosted.org/Flask-JWT/

這裏是我當前的應用程序服務器的實現:

from flask import Flask 
from flask_jwt import JWT, jwt_required, current_identity 
from flask.ext.cors import CORS 
from werkzeug.security import safe_str_cmp 
from wol import User, db 
import hashlib 


def authenticate(username, password): 
    user = User.query.filter_by(username=username).first() 
    print str(user) 
    if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')): 
     return user 


def identity(payload): 
    user_id = payload['identity'] 
    return User.query.filter_by(UserID=user_id) 


app = Flask(__name__) 
CORS(app) 
app.debug = True 
app.config['SECRET_KEY'] = 'super-secret' 

jwt = JWT(app, authenticate, identity) 
admin = User("test", "test1") 
db.session.add(admin) 
db.session.commit() 

@app.route('/protected') 
@jwt_required() 
def protected(): 
    return '%s' % current_identity 


@app.route('/register', methods=['POST']) 
def register(username, password, confirmPassword): 
    # we probably want to hash these passwords when storing in db 
    # we'll hash both the password and confirm password 
    pass_hash = hashlib.sha256(password).hexdigest() 
    conf_pass_hash = hashlib.sha256(confirmPassword).hexdigest() 

    if pass_hash == conf_pass_hash: 
     new_user = User(username, password) 
     db.session.add(new_user) 
     db.session.commit() 

@app.route('/allusers') 
def get_all_users(): 
    users = User.query.all() 
    return users 


if __name__ == '__main__': 
    app.run(host='0.0.0.0') 

,這裏是我的angularjs實現:

(function() { 
     angular.module('loginApp', []).controller('loginController', function($scope, $http) { 
     $scope.data = {}; 

     //we can now process the form 
     $scope.processForm = function() { 
      $http({ 
      method : 'POST', 
      url  : 'http://192.168.0.99:5000/auth', 
      data : $.param($scope.data), // pass in data as strings 
      headers : { 'Content-Type': 'application/json' } // set the headers so angular passing info as form data (not request payload) 
     }) 
      .success(function(data) { 
      console.log("successful") 
      console.log(data); 
      }); 
     }; 
     }); 
    }()); 

我已經設置調試模式下它運行我的Python代碼在服務器上,它返回一個400

+0

400上的響應體是什麼? – univerio

回答

1

哦,這是因爲你使用$.param,其對象序列化到查詢字符串參數,但API希望JSON 。你應該這樣做:

data: JSON.stringify($scope.data) 

改爲。