use*_*695 5 javascript cookies reactjs nextjs
在我的 nextJS 应用程序中,用户可以进行登录(登录页面),这会创建一个带有令牌的 cookie 并重定向到使用主要组件的路由(主页)。
在 Main 组件中,我使用 getInitialProps 来获取 cookie 令牌。但这仅在刷新页面后才有效。所以现在我正在登录并被重定向。如果我单击按钮,则没有令牌。刷新页面后,我确实得到了一个令牌。
我怎样才能避免这种情况?我想我在服务器端做错了什么......
登录
export class Login extends Component {
render () {
return (
<Form id='login' onSubmit={this._onSubmit.bind(this)}>
// Input fields
</Form>
)
}
_onSubmit = (event) => {
event.preventDefault()
const { username, password } = this.state
// Sends mutation request to graphQL server
this.props.signinUserMutation({
variables: { username, password }
}).then(response => {
// Returns token
const token = response.data.token
if (token) {
Cookies.set('auth-token', token)
this.props.client.resetStore().then(() => {
redirect({}, '/main')
})
}
})
}
}
Run Code Online (Sandbox Code Playgroud)
主要的
class Main extends Component {
static async getInitialProps (context, apolloClient) {
const { req } = context
const initProps = {}
if (req && req.headers) {
const cookies = req.headers.cookie
if (typeof cookies === 'string') {
const cookiesJSON = jsHttpCookie.parse(cookies)
initProps.token = cookiesJSON['auth-token']
}
}
return initProps
}
clickIt = () => {
console.log(this.props.token)
}
render () {
return (<Button onClick={this.clickIt.bind(this)})
}
}
Run Code Online (Sandbox Code Playgroud)
登录后,您的 cookie 会保存在浏览器中,因此您应该使用document.cookiegetInitialProps 来获取 cookie 值。
据我理解这段代码:
\n\nif (req && req.headers) {\n const cookies = req.headers.cookie\n if (typeof cookies === \'string\') {\n const cookiesJSON = jsHttpCookie.parse(cookies)\n initProps.token = cookiesJSON[\'auth-token\']\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n正在使用请求标头来获取 cookie 值,这仅在您向服务器发出请求后(刷新页面时)才会发生。当浏览器中发生导航时,代码不会运行,并且您不会获得 cookie。这就是为什么您需要直接从浏览器获取 cookie document.cookie。
考虑使用 localStorage 来保存身份验证令牌而不是 cookie,它有更好的 api。
\n\n由于componentDidMount仅在浏览器中执行,因此使用它来获取 cookie 值并将其放入 redux 存储中:
componentDidMount() {\n placeTokenInReduxStoreAction(Cookies.get(\'auth-token\'));\n}\nRun Code Online (Sandbox Code Playgroud)\n\n我假设你使用cookies-js
\n