我正在使用以下方法通过 jquery 检查登录:
module.exports = {
login: function(username, pass, cb) {
if (localStorage.token) {
if (cb) cb(true)
return
}
this.getToken(username, pass, (res) => {
if (res.authenticated) {
localStorage.token = res.token
if (cb) cb(true)
} else {
if (cb) cb(false)
}
})
},
logout: function() {
delete localStorage.token
},
loggedIn: function() {
return !!localStorage.token
},
getToken: function(username, pass, cb) {
$.ajax({
type: 'POST',
url: '/obtain-auth-token/',
data: {
email_or_username: username,
password: pass
},
success: function(res){
cb({
authenticated: true,
token: res.token
})
}
})
},
}
我的登录验证工作正常,如果用户和密码正确,它将重定向到应用程序页面。但如果不正确,我会在终端收到此消息:
发布http://url_base/obtain-auth-token/ 400(错误请求)
和这个元素:
<p>Bad login information</p>
未出现在我的登录页面上。
我认为问题是来自 jQuery 的错误,但我不知道如何解决这个问题。
我正在使用这个存储库,如何引用:https://github.com/reactjs/react-router/blob/master/examples/auth-flow/auth.js
这是我的登录页面:
“使用严格”
import React from 'react'
import { Router, browserHistory } from 'react-router'
import '../../../css/login.css'
import '../../../css/animation.css'
import Logo from '../icons/Logo'
import auth from './auth'
class LoginPage extends React.Component{
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {
error: false,
loggedIn: auth.loggedIn()
}
}
handleSubmit(ev) {
ev.preventDefault()
var username = this.refs.username.value
var pass = this.refs.pass.value
auth.login(username, pass, (loggedIn) => {
if (loggedIn) {
const { location } = this.props
if (location.state && location.state.nextPathname) {
browserHistory.push(location.state.nextPathname)
} else {
browserHistory.push('app')
}
}
else{
this.setState({error:true});
}
})
}
render() {
return (
<div id="login" className="login">
<div className="login-content">
<div id="login-content-container" className="login-content-container">
<Logo svgClass="login-content-container-logo" width="270" height="35"/>
<form className="login-content-container-form" onSubmit={this.handleSubmit}>
<input className="login-content-container-form-input" type="text" ref="username" placeholder="username"/>
<input className="login-content-container-form-input" type="password" ref="pass" placeholder="password"/>
<button className="login-content-container-form-button">login</button>
</form>
{this.state.error && (
<p>Bad login information</p>
)}
</div>
</div>
</div>
);
}
}
export default LoginPage
最佳答案
这只是因为你没有在getToken中处理ajax错误回调
getToken: function(username, pass, cb) {
$.ajax({
type: 'POST',
url: '/obtain-auth-token/',
data: {
email_or_username: username,
password: pass
},
success: function(res){
cb({
authenticated: true,
token: res.token
})
},
error: function () { cb({authenticated: false}); }
})
},
关于javascript - react 不适用于错误的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38126116/