我在 session 方面遇到问题。由于某种原因,即使我使用的是 req.session 也是未定义的 session 中间件。我试图使用 redis,但无法建立连接。 奇怪的是,由于某种原因,cookie 被注册在 graphql Playground 中。所以原因可能是我传递请求的方式。
所有类型都是正确的( typescript 不会对任何事情生气)。
这是来自 server.ts 的代码
import express, { Request, Response } from "express";
import routes from "./routes";
import cors from "cors";
import "reflect-metadata";
import { createConnection } from "typeorm";
import { ApolloServer } from "apollo-server-express";
import { buildSchema } from "type-graphql";
import session from "express-session";
createConnection()
.then(async (connection) => {
console.log("Conexão feita com sucesso");
const app = express();
app.set("trust proxy", 1);
app.use(cors());
app.use(
session({
name: "qid",
secret: "keyboard cat",
resave: false,
saveUninitialized: true,
cookie: {
secure: false,
maxAge: 1000 * 60 * 60 * 24 * 365 * 10,
httpOnly: true,
},
})
);
const apolloServer = new ApolloServer({
schema: await buildSchema({
resolvers: [
],
validate: false, // Activate the validation with class-validation module.
}),
context: (req: Request, res: Response): Context => ({ req, res, session: req.session }),
playground: {
settings: {
'request.credentials': 'include',
},
},
});
apolloServer.applyMiddleware({ app });
app.use(express.json());
app.use(routes);
app.listen(3333);
})
.catch((error) => console.error(error));
以及我在哪里使用 session 。
@Mutation(() => UserResponse)
async login(
@Arg("info", () => UserLoginInputType) info: UserLoginInputType,
@Ctx(){req, res, session}: Context
): Promise<UserResponse> {
const user = await User.findOneOrFail({ where: { email: info.email } });
const valid = await argon2.verify(user.password, info.password);
if (valid) {
req.session.userId = user.id;
return {
user,
};
}
return {
errors: [
{
field: "password",
message: "Incorrect password",
},
],
};
}
最佳答案
我只是在传递 res 和 req 抛出上下文时忘记了大括号
关于node.js - res.session 未定义 graphql apollo-server-express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65737606/