最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - react-redux redirect to other page after login - Stack Overflow

programmeradmin7浏览0评论

action.js:

export const login = creds => {
    console.log(`${url}/login`);
    const requestOptions = {
        method: "POST",
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json"
        },
        body: creds
    };

    return function(dispatch) {
        dispatch({ type: LOGIN_REQUEST });
        function timer() {
            return fetch(`${url}/login`, requestOptions).then(response => {
                if (!response.ok) {
                    console.log(response);
                    return response.json().then(json => {
                        var error = new Error(json.message);
                        error.response = response;
                        throw error;
                    });
                } else {
                    console.log("3");
                    return response.json();
                }
            }).then(user => {
                if (user.message === "ok") {
                    localStorage.setItem("token", user.token);
                    dispatch({ type: LOGIN_SUCCESS, payload: user.token });
                    window.location.href = `${app}/dashboard`;
                } else {
                    const error = user.message;
                    throw new Error(error);
                }
            }).catch(function(error) {
                dispatch(loginError(error));
            });
        }
        setTimeout(timer, 5000)
    }
};

I am unable to redirect in a single-page manner to my dashboard, I searched a lot but I didn't get anything useful. I am using React Router v4. Can you please suggest whether I am doing this user login with JWT the right way or not.

action.js:

export const login = creds => {
    console.log(`${url}/login`);
    const requestOptions = {
        method: "POST",
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json"
        },
        body: creds
    };

    return function(dispatch) {
        dispatch({ type: LOGIN_REQUEST });
        function timer() {
            return fetch(`${url}/login`, requestOptions).then(response => {
                if (!response.ok) {
                    console.log(response);
                    return response.json().then(json => {
                        var error = new Error(json.message);
                        error.response = response;
                        throw error;
                    });
                } else {
                    console.log("3");
                    return response.json();
                }
            }).then(user => {
                if (user.message === "ok") {
                    localStorage.setItem("token", user.token);
                    dispatch({ type: LOGIN_SUCCESS, payload: user.token });
                    window.location.href = `${app}/dashboard`;
                } else {
                    const error = user.message;
                    throw new Error(error);
                }
            }).catch(function(error) {
                dispatch(loginError(error));
            });
        }
        setTimeout(timer, 5000)
    }
};

I am unable to redirect in a single-page manner to my dashboard, I searched a lot but I didn't get anything useful. I am using React Router v4. Can you please suggest whether I am doing this user login with JWT the right way or not.

Share Improve this question edited Oct 26, 2017 at 14:52 Antti29 3,03312 gold badges36 silver badges36 bronze badges asked Oct 26, 2017 at 12:41 tapan davetapan dave 3032 gold badges8 silver badges18 bronze badges 1
  • I am not familiar with react, but I think it might be a misunderstanding of window.location.href, If you choose to use window.location.href, you should specify the whole path, so for instance maybe window.location.href = localhost:5000/${app}/dashboard. I think this is quite a nice source, stackoverflow.com/questions/7077770/… – cruise_lab Commented Oct 26, 2017 at 12:53
Add a comment  | 

3 Answers 3

Reset to default 10

create a your own history in history.js file using this history library.

//history.js
import createHistory from 'history/createBrowserHistory'

const history = createHistory()

export default history

Supply it to your router:

<Router history = {history}>.....</Router>

Then you can use this history object to redirect from anywhere. In your action:

import history from './history'
history.push(`${app}/dashboard`)
  1. You can add react-router-redux which will conveniently add all routing info to the Redux state, but also you can use push from react-router-redux by:

    dispatch(push('/dashboard'))
    

    You can access it by

    import { push } from 'react-router-redux'
    
  2. I think you are not doing anything wrong with JWT. I would abstract your fetch call with the helper function. I assume you need to add your access token to all future requests after authorization, and using helper function you can do it easier and keep you code cleaner.

window.location.href will hit your server and you'll loose all the benefits of a single page application, you should use a client side routing instead with the history object

In this scenario a good solution could be pass a callback from the component that triggers the first dispatch containing a history.push to the new state

e.g.

Assuming that inside your component props you have access to history

login(body, () => {
  this.props.history.push('/dashboard');
})

then in place of window.location.href = ${app}/dashboard you invoke the callback

发布评论

评论列表(0)

  1. 暂无评论