【发布时间】:2022-01-06 20:14:54
【问题描述】:
我一直在尝试解决这个问题,我只能在登录后获取 accessToken 吗?我一直坚持这个
主要问题是,令牌已经在本地存储中寻找它,但我什至还没有登录。如何让用户在查看本地存储之前先登录
requestMethod.js
import axios from 'axios'
const BASE_URL = 'http://localhost:5000/api'
const TOKEN = JSON.parse(JSON.parse(localStorage.getItem('persist:root')).user)
.currentUser.accessToken
export const publicRequest = axios.create({
baseURL: BASE_URL,
})
export const userRequest = axios.create({
baseURL: BASE_URL,
headers: { token: `Bearer ${TOKEN}` },
})
登录.jsx
import { useEffect } from "react"
import { useState } from "react"
import { useDispatch } from "react-redux"
import { useHistory } from "react-router"
import { login } from "../../redux/apiCalls"
import { userRequest } from "../../requestMethod"
const Login = () => {
let history = useHistory()
const [username, setUsername] = useState("")
const [password, setPassword] = useState("")
const dispatch = useDispatch()
const handleClick = (e) =>{
e.preventDefault()
login(dispatch,{username,password})
history.push('/home')
}
useEffect(() =>{
try {
} catch (error) {
}
},[])
return (
<div style={{display: 'flex', alignItems:"center", justifyContent:"center", height: '100vh', flexDirection: "column"}}>
<form action="">
<input style={{padding: 10, marginBottom:20}} value={username} type="text" placeholder="username" onChange={e => setUsername(e.target.value)} />
<input style={{padding: 10, marginBottom:20}} value={password} type="password" placeholder="password" onChange={e => setPassword(e.target.value)} />
<button style={{padding: 10, width: 100}} onClick={handleClick}>Login</button>
</form>
</div>
)
}
export default Login
apicalls.js
import { loginFailure, loginStart, loginSuccess } from './userRedux'
export const login = async (dispatch, user) => {
dispatch(loginStart())
try {
const res = await publicRequest.post('/auth/login', user)
const TOKEN = JSON.parse(
JSON.parse(localStorage.getItem('persist:root')).user
).currentUser.accessToken
dispatch(loginSuccess(res.data))
} catch (error) {
dispatch(loginFailure())
}
}
【问题讨论】:
-
如果你的应用有登录的概念,那它一定有session的概念。
-
嵌套的 JSON.parse() 看起来很奇怪
标签: javascript reactjs api axios mern