[英]How to validate token from Localstorage and return currentUser from Apollo Server to React front-end?
I already have a jwt middleware which verifies token and returns currentUser to React front-end: 我已经有一个jwt中间件验证令牌并将currentUser返回到React前端:
app.use(async (req, res, next) => {
const token = req.headers['authorization'];
if(token !== "null") {
try{
const currentUser = await jwt.verify(token, process.env.SECRET)
} catch {
console.error(err);
}
}
next();
});
Now, I want to integrate the logic into the following Apollo server: 现在,我想将逻辑集成到以下Apollo服务器中:
const app = express();
const server = new ApolloServer({
typeDefs: gql(typeDefs),
resolvers,
context: async () =>({
db,
secret: process.env.SECRET,
}),
});
app.use(cors(corsOptions));
server.applyMiddleware({ app });
At the end, the value of currentUser should be available to be used at react front-end. 最后,currentUser的值应该可用于react前端。
How can I achieve this? 我怎样才能做到这一点?
You can add the currentUser
to the request
object inside the middleware. 您可以将
currentUser
添加到中间件内的request
对象。 Next, you pass it copy it from the request to the GraphQL context. 接下来,您将其从请求复制到GraphQL上下文。 Then you can add a
currentUser
resolver and simply return the user from the context. 然后,您可以添加
currentUser
解析程序,只需从上下文中返回用户。
Your middlware 你的middlware
app.use(async (req, res, next) => {
const token = req.headers['authorization'];
if(token !== "null") {
try{
req.currentUser = await jwt.verify(token, process.env.SECRET)
} catch {
console.error(err);
}
}
next();
});
Your server 你的服务器
const app = express();
const server = new ApolloServer({
typeDefs: gql(typeDefs),
resolvers,
context: ({ req }) =>({
currentUser: req.currentUser,
db,
secret: process.env.SECRET,
}),
});
app.use(cors(corsOptions));
server.applyMiddleware({ app });
and the resolvers 解析器
const resolvers = {
Query: {
currentUser: (parent, args, context) => context.currentUser,
...
}
}
Add the corresponding type definition and you should be able to query the current user from your client. 添加相应的类型定义,您应该能够从客户端查询当前用户。
If you need more information here is a detailed tutorial which might be of help. 如果您需要更多信息,请参阅详细的教程 ,这可能会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.