在该程序的整个生命周期中,我都无法弄清楚为什么未在浏览器中保存此cookie。如果我运行graphql游乐场(与服务器相同,位于端口4000上),则会话ID将存储在浏览器中没问题。我启用了cors,因此不应阻止此操作。但是,如果我从其他任何URL发送登录请求,它将不会将其保存在浏览器中。我尝试了多种浏览器,但不会在其中任何一种上保存,并且我尝试记录会话以确保实际上已保存它们。有什么想法吗?
const { GraphQLServer } = require('graphql-yoga');
const session = require('express-session');
const bcrypt = require('bcryptjs');
const ms = require('ms');
const typeDefs = `
type Query {
isLoggedIn: Boolean!
}
type Mutation {
logIn(email: String!, password: String!): Boolean!
signUp(email: String!, password: String!): Boolean!
}
`
// mock mockDBbase
const mockDB = {};
const resolvers = {
Query: {
// is the user authenticated
isLoggedIn: (parent, args, ctx) => {
return ctx.session.isLoggedIn === true;
}
},
Mutation: {
// user can sign up for a new account
signUp: async (parent, { email, password }, ctx) => {
// if user is already in the DB
if (mockDB[email]) {
throw new Error('This user already exists, please log in.');
}
const saltRounds = 14; // roughly 1.5 secs on 2GHZ CPU
// store password in mock DB (replace with real DB)
mockDB[email] = {
// salt and hash pw
password: await bcrypt.hashSync(password, saltRounds),
};
return true;
},
// authenticates user into respective account
logIn: async (parent, { email, password }, ctx) => {
// grab user from DB
const user = mockDB[email];
if (user) {
// make sure pw matches
if (await bcrypt.compareSync(password, user.password)) {
// set user logged in flag
ctx.session.isLoggedIn = true;
return true;
}
throw new Error('User email or password is incorrect.');
}
throw new Error('User email or password is incorrect.');
}
}
}
// opts
const opts = {
port: 4000,
cors: {
credentials: true,
origin: "*"
}
};
// context
const context = req => ({
session: req.request.session,
});
// server
const server = new GraphQLServer({
typeDefs,
resolvers,
context,
});
const SESSION_SECRET = 'my-super-secret-secret';
server.express.set('trust proxy', 1) // trust first proxy
// session middleware
server.express.use(
session({
name: 'SSID',
// change this to randomly generate a secret
secret: SESSION_SECRET,
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: process.env.NODE_ENV === 'production',
maxAge: ms('1d'),
}
})
);
// start server
server.start(opts, () => console.log(`Server is running on http://localhost:${opts.port}`));