我正在创建一个API,以将基本的auth登录请求发送到我的Flask后端,但是在发送请求时,我得到了
{username: "ww", password: "ww"}
POST http://localhost:5000/login 401 (UNAUTHORIZED)
我已经记录了要检查的输入数据已被设置,此响应通过浏览器上的js控制台返回,在我的flask控制台中的记录如下:
127.0.0.1 - - [10/Nov/2019 16:21:07] "OPTIONS /login HTTP/1.1" 200 -
{'username': '', 'password': ''}
127.0.0.1 - - [10/Nov/2019 16:21:07] "POST /login HTTP/1.1" 401 -
我的烧瓶登录路径如下
@app.route('/login', methods =['POST'])
def login():
if request.method == 'POST':
auth = request.authorization
print(auth)
if not auth.username or not auth.password:
return make_response('Could not verify :(', 401, {'WWW-Authenticate' : 'Basic realm="Login Required"'})
user = User.query.filter_by(username = auth.username).first()
if not user:
return make_response('Could not verify', 401, {'WWW-Authenticate' : 'Basic realm="Login Required"'})
if check_password_hash(user.password, auth.password):
token = jwt.encode({'public_id' : user.public_id, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=30) }, app.config['SECRET_KEY'])
return jsonify({'token' : token.decode('UTF-8')})
return make_response('Could not verify', 401, {'WWW-Authenticate' : 'Basic realm="Login Required"'})
这是我的反应前端上的登录组件 导出类Login扩展了React.Component {
constructor(props){
super(props);
this.state = {
username: '',
password: '',
}
}
changeHandler = e => {
this.setState({[e.target.name]: e.target.value})
}
submitHandler = e => {
const headers = {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
}
var username = this.username
var password = this.password
e.preventDefault()
console.log(this.state)
axois.post('http://localhost:5000/login',this.state,{
headers: {
headers
}
,auth: {
username : username,
password: password
}
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
}
render() {
const {username, password} = this.state
return <div className = "base-container" ref={this.props.containerRef}>
<div className="content">
<div className="logo">
<img src={Logo} alt="Logo"/>
</div>
<form className="form" onSubmit={this.submitHandler}>
<div className="form-group">
<label htmlFor="username"> Username</label>
<input type="text"
name="username"
value ={username}
placeholder="Username"
onChange={this.changeHandler}/>
</div>
<div className="form-group">
<label htmlFor="password"> Password</label>
<input type="password"
name="password"
value={password}
placeholder="Password"
onChange ={this.changeHandler}/>
</div>
<button type="submit" className="btn">Login</button>
</form>
</div>
<div className="footer">
</div>
</div>
}
}
我的请求通过使用邮递员来工作,所以不确定为什么不使用React?我正在使用Flask-Cors来防止CORS错误并将用户数据存储在auth标头中,所以我不确定为什么flask无法读取它。
我对此很陌生,所以任何帮助都将非常棒:)谢谢!