将身份验证数据保存在LocalStorage react js上

时间:2019-04-15 13:14:30

标签: javascript reactjs local-storage axios

我正在用Reactjs开发一个应用程序,并使用axios来处理请求,我需要将用户数据保存在localStorage中,但是这在我的代码中丢失了一些东西,因为它在值中未定义成为我需要的数据。

文件SingUp

class SignIn extends Component {

    constructor(props) {
        super(props);
        this.state = { value: "" };
    }

    handleSignIn = async e => {
        e.preventDefault();
        const { email, password } = this.state;
        if (!email || !password) {
        this.setState({ error: "Preencha e-mail e senha para continuar!" });
        } else {
            try {            
                const response = await api.post("login", querystring.stringify({ email, password }));            
                login(response.data.token);
                console.log('ttttt', login(response.data.token));            
                this.props.history.push("/menu");
            } catch (err) {
                this.setState({
                error:
                    "Houve um problema com o login, verifique suas credenciais. T.T"
                });
            }
        }        
    };

***********************

    <form onSubmit={this.handleSignIn}>
    {this.state.error && <p>{this.state.error}</p>}
        <div className="form-group">
            <label>Email:</label>
            <input
                type="email"
                placeholder="E-mail"
                onChange={e => this.setState({ email: e.target.value })}
                className='form-control'
            />
            <br />
            <label>Senha:</label>
            <input
                type="password"
                placeholder="Password"
                onChange={e => this.setState({ password: e.target.value })}
                className='form-control'
            />
        </div>
        <div className='row'>
            <div className='col-md-4'>                            
                <button type="submit" >Log In</button>
            </div>
        </div>
    </form> 

***********************

API文件

import axios from "axios";
import { getToken } from "./auth.js";

const api = axios.create({
    baseURL: "https://localhost/aplicacao",
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
});

api.interceptors.request.use(async config => {
    const token = getToken();
    if (token) {
        config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
});

export default api;

验证文件

export const TOKEN_KEY = localStorage;
export const isAuthenticated = () => localStorage.getItem(TOKEN_KEY) !== null;
export const getToken = () => localStorage.getItem(TOKEN_KEY);
export const login = token => {
    localStorage.setItem(TOKEN_KEY, token);
};
export const logout = () => {
    localStorage.removeItem(TOKEN_KEY);
};

Package.json文件

{
  "name": "teste1",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "directories": {
    "test": "test"
  },
  "scripts": {
    "build": "webpack --config webpack.prod.js",
    "start": "webpack-dev-server --config webpack.dev.js",
    "test": "jest ./test"
  },
  "jest": {
    "setupTestFrameworkScriptFile": "./test/enzyme.setup.js"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.2.3",
    "@babel/core": "^7.3.4",
    "@babel/plugin-proposal-class-properties": "^7.3.4",
    "@babel/preset-env": "^7.3.4",
    "@babel/preset-react": "^7.0.0",
    "babel-core": "^7.0.0-bridge.0",
    "babel-jest": "^23.6.0",
    "babel-loader": "^8.0.5",
    "babel-polyfill": "^6.26.0",
    "clean-webpack-plugin": "^1.0.0",
    "cors": "^2.8.5",
    "css-loader": "^2.0.0",
    "enzyme": "^3.6.0",
    "enzyme-adapter-react-16": "^1.5.0",
    "html-webpack-plugin": "^3.2.0",
    "jest": "^23.6.0",
    "node-sass": "^4.9.3",
    "react-router-dom": "^4.3.1",
    "react-test-renderer": "^16.8.4",
    "sass-loader": "^7.1.0",
    "style-loader": "^0.23.0",
    "url-loader": "^1.1.2",
    "webpack": "^4.27.1",
    "webpack-cli": "^3.1.2",
    "webpack-dev-server": "^3.1.8",
    "webpack-merge": "^4.1.4"
  },
  "dependencies": {
    "axios": "^0.18.0",
    "react": "^16.8.4",
    "react-check-auth": "^0.2.0-alpha.2",
    "react-dom": "^16.8.4"
  }
}

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

如果令牌将作为cookie传递给客户端,则应在HTTP响应的set-cookie标头下找到它。您可以在axios中以response.headers['set-cookie']的身份访问它。由于标头的语法为key=value,因此可能需要进一步解析。就您而言,它看起来像token=1234567890abcdef

请注意,您提供的示例响应似乎未包含此标头。您首先需要得到一个响应。

尽管有一个可疑的错误,其余的似乎仍在工作。在您的Auth文件的第一行

export const TOKEN_KEY = localStorage;

您可能想变得更像

export const TOKEN_KEY = 'some-string';

您将localStorage对象用作键,这没有任何意义,但是javascript的类型强制将其字符串化为'[object Storage]'

localStorage中的键值对'[object Storage]'undefined表明令牌已正确保存。标头Authorization: Bearer undefined表示令牌也正确包含在您的请求中。令牌恰好是undefined