我正在尝试使用我的 API 后端设置 React 身份验证。 API 后端使用电子邮件和密码,并为每个新用户创建一个 token 。所有这些都是通过直接 JSON 而不是 JWT 提供的,所以我使用 Auth0 tut还有这个Stack q/a作为起点。
我的第一个目标是进行简单的登录和重定向。我已经连接了 action/reducer,现在正在进行 API 调用。我正在使用基本的身份验证调用,并将其转换为 64 位字符并通过 header 发送。这些都通过 Postman 进行了测试和工作。
当我执行当前的 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(Reducer)
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 组件
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 组件
`_handleChange(eventKey) {
< AuthorizeLogin onLoginClick={this.props.onLogin}/>);
`
HomePage.js 容器
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'...
。
未经测试,但是,它应该让您“我在这里”。
最后,包装箭头函数 {}
关于reactjs - React 和 Redux HTTP header 授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39168801/