I am using the graphql-HTTP package. And there is no tab for passing tokens (headers) in the playground. So how to enable it?
I'm declaring as below
app.use(
"/graphql",
graphqlHTTP({
schema: UserTypes,
rootValue: UserResolver,
graphiql: true,
})
);
First of all, the graphqlHTTP
function comes from the express-graphql
package, not the graphql-http
package.
When using the express-graphql
package and graphqlHTTP
function. You can use headerEditorEnabled option to enables the header editor
An optional boolean which enables the header editor when
true
. Defaults tofalse
.
E.g.
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
const schema = buildSchema(`
type Query {
hello: String
}
`);
const root = {
hello: () => {
return 'Hello, World';
}
};
const app = express();
app.use(
'/graphql',
graphqlHTTP((req) => {
console.log('req.headers: ', req.headers)
return {
schema,
rootValue: root,
graphiql: { headerEditorEnabled: true }
}
})
);
const port = 4000;
app.listen(port, () => {
console.log(`Server is listening on http://localhost:${port}`);
});
The header editor will display
Send a graphql HTTP request, the logs:
Server is listening on http://localhost:4000
req.headers: {
host: 'localhost:4000',
connection: 'keep-alive',
'content-length': '42',
'sec-ch-ua': '"Microsoft Edge";v="113", "Chromium";v="113", "Not-A.Brand";v="24"',
accept: 'application/json',
'content-type': 'application/json',
'sec-ch-ua-mobile': '?0',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42',
token: 'bearer 123',
'sec-ch-ua-platform': '"macOS"',
origin: 'http://localhost:4000',
'sec-fetch-site': 'same-origin',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
referer: 'http://localhost:4000/',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6'
}
You can access the token
header from req.headers.token