node.js - 如何将参数传递给 graphqlHTTP 中间件
问题描述
我如何将参数传递给 graphqlHTTP 中间件
我正在尝试将授权标头令牌有效负载从另一个上层中间件传递给 graphqlHTTP 中间件
app.use('/private', (req:Request,res:Response,next:Function) => {
if(!req.header('Authorization')){
res.json({
error:true,
message:'Authorization bearer required'
})
}else{
const token = Buffer.from(req.header('Authorization').split('Bearer ')[1], 'base64').toString('ascii');
if(decode(token)){
next();
}else{
res.json({
error:true,
message:'Authorization bearer required'
})
}
}
});
app.use('/private', graphqlHTTP({
schema:privateSchema,
graphiql:false
}))
解决方案
在请求本身中从中间件设置数据是很常见的。
在您的场景中,可以将令牌设置为req.token
然后传递给您的 graphql 解析器上下文,例如:
// main.js
app.use(authMidddleware) // sets req.token
app.use(
'/graphql',
bodyParser.json(),
graphqlExpress(req => ({ schema, context: req }))
)
// some-resolver.js
export const myResolver = {
Query: {
token: async (parent, { input }, context) => {
const { token } = context;
// other stuff
}
}
}
推荐阅读
- performance - 为什么 strconv.ParseUint 比 strconv.Atoi 慢?
- html - 如何防止用户使浏览器窗口比 HTML 和 CSS 中的预定义宽度窄?
- python - 使用透明背景保存 Matplotlib 表面图
- javascript - 无法检索用户的 mysite URL OneDrive 资源管理器 javascript 问题
- r - 如何将数据框中的所有整数 64 列转换为整数?
- stata - 修改所有可能的 stata ado 文件,使其接受任意数量的变量
- javascript - 使用 puppeteer 检测 DOM 中的变化 _ MutationObserver 正在工作
- css - 具有特定布局的卡片网格
- ubuntu - 在 Ubuntu 上由 Code Runner 运行 Python 代码时出现 Visual Studio Code 错误
- reactjs - Firebase 分页使用时间戳/日期作为 orderBy