javascript - 如何验证来自 Localstorage 的令牌并将 currentUser 从 Apollo Server 返回到 React 前端?
问题描述
我已经有一个 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();
});
现在,我想将逻辑集成到以下 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 });
最后, currentUser 的值应该可以在反应前端使用。
我怎样才能做到这一点?
解决方案
您可以将 添加currentUser
到request
中间件内的对象中。接下来,您将其从请求中复制到 GraphQL 上下文中。然后您可以添加一个currentUser
解析器并简单地从上下文中返回用户。
你的中间件
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();
});
你的服务器
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 });
和解析器
const resolvers = {
Query: {
currentUser: (parent, args, context) => context.currentUser,
...
}
}
添加相应的类型定义,您应该能够从您的客户端查询当前用户。
如果您需要更多信息,这里有一个可能会有所帮助的详细教程。
推荐阅读
- java - 我可以重载Java中的接口吗?
- mysql - 将数据从 s3 加载到 mysql aurora
- angular - Angular 6 - 登录错误以返回 http 状态 403
- vue.js - 正确设置 prerender-spa-plugin
- html - 引导文本中的文本-井不会居中
- java - Java 和 Xerces:找不到属性 XMLConstants.ACCESS_EXTERNAL_DTD
- javascript - 使用 jquery 中的每个循环的 Next 和 Prev 按钮功能
- c - C 和 MATLAB:在 C 中创建空数组调用 Matlab 函数来填充它以错误结尾
- c++ - 如何在 C++ DLL 项目中使用第 3 方 DLL?
- cloud-foundry - 计划重启 Pivotal Cloud Foundry 上的应用程序