编辑:
我在连接用户时设置了cookie,并将令牌存储在cookie中。并使用GetInitialProps
i访问cookie,然后检查会话是否设置为用户。
[似乎只有当我使用链接:例如进入此页面的主页时访问此页面时才起作用,但是当我键入URL时它不起作用。
我正在使用npm install --save next-cookies
来检索Cookie:https://www.npmjs.com/package/next-cookies
对不起,这可能是一个愚蠢的问题,但我仍在学习...
这是我页面Login.js的全部代码
import React, { Component, useState } from 'react'
import Parse from 'parse'
import Snackbar from '@material-ui/core/Snackbar';
import Cookies from 'js-cookie'
import cookies from 'next-cookies'
export default function login() {
const [state, setState] = React.useState({
username: "",
password: "",
}
)
const [error, setError] = useState(false)
async function handleConnection() {
try {
const user = await Parse.User.logIn(state.username, state.password)
console.log(user)
var currentUser = Parse.User.current();
const token = currentUser.getSessionToken()
//console.log(token)
Cookies.set('token', token, { expires: 365 })
setError(false)
} catch (e) {
setError(true)
}
}
function handleChange(evt) {
const value = evt.target.value;
setState({
...state,
[evt.target.name]: value
});
}
return (
<div className="notConnected container-fluid">
<div className="containerFormLogin">
<h1>Connectez-vous !</h1>
<p>{error ? "Nom d'utilisateur ou mot de passe incorrect" : ''}</p>
<label>Nom d'utilisateur ou mail</label>
<input type="text" name="username" onChange={handleChange} />
<label>Mot de passe</label>
<input type="password" name="password" onChange={handleChange} />
<button className="pulse" onClick={handleConnection}>Se connecter</button>
<p>Pas encore de compte ? Inscrivez-vous par ici !</p>
<Snackbar
anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
open={error}
autoHideDuration={3000}
message={<span id="message-id">Impossible de se connecter, vérifier vos informations de connexion</span>}
ContentProps={{
"aria-describedby": "message-id"
}}
></Snackbar>
</div>
<style jsx>{`
.notConnected
{
background-image: url('/images/notConnected.svg');
height: 100vh;
width: 100%;
background-position: center;
background-size: cover;
background-repeat: no-repeat;
display: flex,
}
p:empty
{
margin:0 !important;
}
.containerFormLogin
{
width: 400px;
background-color: rgba(255,255,255, 0.8);
box-shadow: rgba(0,0,0, 0.5) 10px 10px 10px;
border-radius: 10px;
display: flex;
flex-direction: column;
padding: 30px;
margin:auto;
transition: all .2s ease-in;
}
.containerFormLogin:hover
{
background-color: rgba(255,255,255, 1);
}
.containerFormLogin h1
{
margin-bottom: 40px;
font-family: 'Raleway', sans-serif;
font-size: 25px;
text-align: center;
}
.containerFormLogin p
{
font-size: 12px;
font-family: 'Raleway', sans-serif;
margin-top: 10px;
}
.containerFormLogin label
{
font-size: 12px;
font-family: 'Raleway', sans-serif;
}
.containerFormLogin input
{
margin-bottom: 20px;
font-family: 'Raleway', sans-serif;
font-size: 15px;
padding-top: 10px;
padding-bottom: 10px;
}
.error
{
border-color: red;
}
button
{
background: none;
border: 2px solid;
font: inherit;
line-height: 1;
padding: 1em 2em;
color: #ef6eae;
-webkit-transition: 0.25s;
transition: 0.25s;
}
button:hover, button:focus {
border-color: #ef8f6e;
color: #ef8f6e;
}
.pulse:hover,
.pulse:focus {
-webkit-animation: pulse 1s;
animation: pulse 1s;
box-shadow: 0 0 0 2em rgba(255, 255, 255, 0);
}
@-webkit-keyframes pulse {
0% {
box-shadow: 0 0 0 0 #ef8f6e;
}
}
@keyframes pulse {
0% {
box-shadow: 0 0 0 0 #ef8f6e;
}
}
`}</style>
</div >
)
}
login.getInitialProps = (ctx) => {
const allCookies = cookies(ctx).token;
const UserToken = Parse.User.me(allCookies)
if (UserToken) {
// the user is connected so we do the redirection beacause when he's connected he can't have access to this page
return (
UserToken
)
} else {
// Do something else
}
}
编辑#2:
当我到达带有首页到登录页面的链接的页面时,出现此错误
Unhandled Rejection (TypeError): res is undefined
并且当我重新加载页面时,或者如果我通过他的网址访问,他都会给我另一个错误:
ReferenceError: localStorage is not defined
这是我的getInitialProps:
connexion.getInitialProps = ({ ctx, res }) => {
const cookies = Cookies.get('tokenUserParse');
const UserToken = Parse.User.me(cookies)
if (UserToken) {
// the user is connected so we do the redirection beacause when he's connected he can't have access to this page
res.writeHead(403, {
Location: '/'
});
res.end();
} else {
// Do something else
}
}
[您需要了解,getInitialProps
中具有的相同代码将同时在服务器(Node.js环境)和浏览器(javascript)中运行。有些库在两种环境下都可以正常工作,但有些库则不能。因此有时您需要根据运行代码的环境执行不同的操作。类似这样的方法可以解决您的问题:
const isServer = typeof window === 'undefined';
const Parse = isServer ? require('parse/node') : require('parse');
connexion.getInitialProps = async ({ ctx, res }) => {
const cookies = Cookies.get('tokenUserParse');
const UserToken = await Parse.User.me(cookies)
if (UserToken) {
// the user is connected so we do the redirection beacause when he's connected he can't have access to this page
if (isServer) {
res.writeHead(302, {
Location: '/'
});
res.end();
} else {
document.location.href = '/'
}
} else {
// Do something else
}
}