在外部链接中重定向时如何保存用户名和密码

时间:2019-04-23 07:06:27

标签: reactjs react-router axios

我创建一个登录页面,登录后必须重定向到外部链接,如何保存用户并传递登录信息?单击按钮登录后,我需要我的用户登录外部网站

我使用

"axios": "^0.18.0","react": "^16.8.5",
"react-dom": "^16.8.5",
"react-router": "^5.0.0",
"react-router-dom": "^5.0.0",
        e.preventDefault()
        axios.defaults.withCredentials = true;


        const bodyParameters = {
            params: {
                username: this.state.username,
                password: this.state.password,
                appType: this.state.appType
            }
        }


        axios.get(
            'http://localhost:8080/test/api',
            bodyParameters,

            {
                withCredentials: true
            }
        ).then((response) => {
            if (response.data.hasError !== true) {
                const token = localStorage.setItem('token', response.data.token)



                axios.defaults.headers['Authorization'] = "Bearer " + localStorage.getItem('token');

                window.location = 'http://localhost:8082/test'
                return response.data

            } else {
             console.log('error')
            }


        }).catch((error) => {

        });

1 个答案:

答案 0 :(得分:2)

您可以使用本地存储-

       axios({
          method: 'post',
          url: 'http://localhost:4000/login',
        data: {
            user_email: formData.user_email.value,
            user_password: formData.user_password.value,
        }
    }).then(res => {
        if (res && !res.data.error) {
            localStorage.setItem('sessionID', res.data.data.sessionID);
            localStorage.setItem('token', res.data.data.token);
            localStorage.setItem('sessionEmail', res.data.data.sessionEmail);
            localStorage.setItem('notify', JSON.stringify({msg: res.data.message, type: 'success'}));
            this.props.history.push("/testlist");
        } else if (res.data.error) {
            localStorage.setItem('notify', JSON.stringify({msg: res.data.message, type: 'error'}));
        }else if ( !res.data.error) {
            localStorage.removeItem('token', res.data.data.token);
            localStorage.setItem('notify', JSON.stringify({msg: res.data.message, type: 'error'}));
        } else {
            localStorage.setItem('notify', JSON.stringify({msg: res.data.message, type: 'error'}));
        }
    }, err => {
        console.log(err);
        localStorage.setItem('notify', JSON.stringify({msg: '500 api error', type: 'error'}));
    });
}