我使用会话身份验证实现了后端,但是当我通过 insominia 发出请求时,我无法连接到我的前端应用程序,可以将会话 id 保存在我的 cokkies 中,但是在前端 NEXT.js 中,当我发出请求时,不会保存任何内容。 我该怎么做?
我已经阅读了有关下一个身份验证的所有内容,但是我可以找到类似的内容。
我的身份验证上下文在前面
import { createContext } from 'react';
type AuthContextType = {
isAuthenticated: boolean;
signIn: ({ email, password }: { email: string, password: string }) => Promise<void>;
};
export const AuthContext = createContext({} as AuthContextType);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const isAuthenticated = false;
async function signIn({ email, password }: { email: string, password: string }): Promise<void> {
// Implementação da função signIn
//fazer request para minha api backend que vai retornar um session cookie
const response = await fetch('http://localhost:3000/auth/login', {
method: 'POST',
body: JSON.stringify({ email, password }),
headers: {
'Content-Type': 'application/json'
}
})
console.log(response.json());
}
return (
<AuthContext.Provider value={{ isAuthenticated, signIn }}>
</AuthContext.Provider>
);
}
我如何在前面的表格中提出请求。
function LoginPage() {
const [email, setEmail] = useState(''); // Use useState para controlar o email
const [password, setPassword] = useState(''); // Use useState para controlar a senha
const { signIn } = useContext(AuthContext)
const handleLogin = async (event: any) => {
event.preventDefault();
const data = {
email: email,
password: password
};
try {
const response = await signIn(data);
console.log(response);
Router.push('/dashboard');
} catch (err) {
console.log(err);
}
}
这是我的后端app.js
async function bootstrap() {
const app = await NestFactory.create(AppModule, { cors: true });
const PORT = Number(process.env.SERVER_PORT) || 3000;
const client = redis.createClient({ url: process.env.REDIS_URL });
const RedisStore = connectRedis(session);
app.use(
session({
name: 'session',
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
store: new RedisStore({
client,
ttl: 86400,
}),
cookie: {
maxAge: 24 * 60 * 60 * 1000,
},
}),
);
app.use(passport.initialize());
app.use(passport.session());
await app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
}
各位,我明白了。
我只将 cors 配置放在后端中,允许我的前端,并将 include 放在我的 authcontext 中。
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as session from 'express-session';
import * as passport from 'passport';
import * as connectRedis from 'connect-redis';
import * as redis from 'redis';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const allowedOrigins = ['http://localhost:3001'];
app.enableCors({
origin: (origin, callback) => {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
credentials: true,
});
const PORT = Number(process.env.SERVER_PORT) || 3000;
const client = redis.createClient({ url: process.env.REDIS_URL });
const RedisStore = connectRedis(session);
app.use(
session({
name: 'session',
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
store: new RedisStore({
client,
ttl: 86400,
}),
cookie: {
maxAge: 24 * 60 * 60 * 1000,
},
}),
export const AuthContext = createContext({} as AuthContextType);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const isAuthenticated = false;
async function signIn(signInDto: signInDto) {
const response = await fetch(`${API_URL}/auth/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
// credentials: 'include',
body: JSON.stringify(signInDto),
});
const data = await response.json();
if (response.ok) {
return data.message;
}
throw new Error(data.message);
}