我正在嘗試使用我的API後端安裝React身份驗證。 API後端使用電子郵件和密碼,併爲每個新用戶創建一個令牌。所有這些都是通過直接的JSON提供的,而不是JWT提供的,所以我使用Auth0 tut和Stack q/a作爲起始位置。React和Redux HTTP頭授權
我的第一個目標是做一個簡單的登錄和重定向。我將動作/縮減器連接起來了,現在我正在進行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元器件
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);
您提到該頁面重新加載;你可能使用'form'標記並忘記了'event.preventDefault()'? –
我將它添加到組件中的onClick函數中。如果他們打電話給另一個行動,我是否需要將其添加到我的行動或減速器中的某個地方? –
你可以顯示該代碼嗎?我認爲這個問題可能在你的'HomeHeader'組件中。 –