我试图设置一个React认证与我的API后端。API后端使用电子邮件和密码,并为每个新用户创建令牌。所有这些都是通过直接JSON提供的,而不是JWT,所以我使用Auth0 tut和这个堆栈q/a作为起点。
我的第一个目标是做一个简单的登录和重定向。我将action/reducer连接起来,现在我正在进行API调用。我使用一个基本的认证调用,并将其转换为64位字符,并通过报头发送。
当我做这个当前的React设置,它得到"抓取"在控制台,但从来没有"我在这里。",页面重新加载。我不知道在哪里解决这个问题,让它授权和重定向。知道我哪里做错了吗?
HomePage.js(容器)
class HomePage extends React.Component {
constructor(props) {
super(props);
}
render() {
const { dispatch, isAuthenticated } = this.props;
return (
<div>
< HomeHeader onLogin={this.props.onLogin} />
</div>
);
}
}
function mapStateToProps(state) {
return { loginResponse: state.loginResponse };
}
function mapDispatchToProps(dispatch) {
return {
onLogin: (creds) => dispatch(loginUser(creds)),
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(HomePage);
AuthorizationActions.js(操作)
function requestLogin(creds) {
return {
type: types.LOGIN_REQUEST,
isFetching: true,
isAuthenticated: false,
creds
}
}
function receiveLogin(user) {
return {
type: types.LOGIN_SUCCESS,
isFetching: false,
isAuthenticated: true,
id_token: user.id_token
}
}
export function loginUser(creds) {
**console.log("Fetching");**
const hash = new Buffer(`${creds.username}:${creds.password}`).toString('base64')
return fetch('http://api.xxx.dev/sessions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic ${hash}'
},
})
.then(response => {
**console.log("I'm here");**
if(response.status >= 200 && response.status < 300){
console.log("Response; ", response);
// Dispatch the success action
dispatch(receiveLogin(user));
localStorage.setItem('id_token', user.id_token);
} else {
const error = new Error(response.statusText);
error.response = response;
dispatch(loginError(user.message))
throw error;
}
})
.catch(error => { console.log('Request Failed: ', error);});
}
AuthorizationReducer.js(减速器)
import { browserHistory } from 'react-router';
import Immutable from 'immutable';
const initialState = new Immutable.Map({
username: '',
password: '',
isLoggingIn: false,
isLoggedIn: false,
isFetching: false,
error: null,
isAuthenticated: localStorage.getItem('id_token') ? true : false
});
function authenticationReducer(state = initialState, action) {
switch ( action.type ) {
case 'LOGIN_REQUEST':
return { ...state,
isFetching: true,
isAuthenticated: false,
user: action.creds
}
case 'LOGIN_SUCCESS':
return {
...state,
browserHistory: browserHistory.push('/dashboard')
}
case 'LOGIN_FAILURE':
return alert('Crap, there are login failures');
default:
return state;
}
}
export default authenticationReducer;
configureStore.js(存储)
const middleware = applyMiddleware(
thunk,
apiMiddleware,
global.window ? logger : store => next => action => next( action )
);
const store = createStore( reducers, initialState, compose(middleware, window.devToolsExtension ? window.devToolsExtension() : f => f ))
<AuhorizeLogin.js组件/strong>
constructor(props, context) {
super(props, context);
this.state = {};
this._login = this._login.bind(this);
}
_login(e) {
e.preventDefault;
const email = this.refs.email;
const password = this.refs.password;
const creds = { email: email.value.trim(), password: password.value.trim() };
this.props.onLoginClick(creds);
}
<HomeHeader.js组件/strong>
`_handleChange(eventKey) {
< AuthorizeLogin onLoginClick={this.props.onLogin}/>);
`
<HomePage.js容器/strong>
constructor(props) {
super(props);
}
render() {
const { dispatch, isAuthenticated } = this.props;
return (
...
< HomeHeader onLogin={this.props.onLogin} />
...
)
}
function mapStateToProps(state) {
return {
loginResponse: state.loginResponse,
};
}
function mapDispatchToProps(dispatch) {
return {
onLogin: (creds) => dispatch(loginUser(creds)),
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(HomePage);
尝试使用return fetch('http://api.xxx.dev/sessions'...
。虽然没有测试过,但应该能让你感觉到"我在这里"。最后,包装箭头函数{}