我目前正在创建一个小应用程序并遇到了问题。我正在使用flask jwt模块,以便用户检索令牌以便能够访问在python中公开的api。我正在使用angularjs进行前端开发。当我尝试登录我的api驻留的服务器时返回400错误
"POST /auth HTTP/1.1" 400
根据文档,我所要做的就是将我的凭据传递给auth端点,我应该能够取回页面上显示的令牌: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 :(得分:1)
哦,这是因为您正在使用$.param
,它将对象序列化为查询字符串参数,但API需要JSON。你应该这样做:
data: JSON.stringify($scope.data)
代替。