javascript 如何在graphiql playground中启用Header部分?

3z6pesqy  于 2023-05-21  发布在  Java
关注(0)|答案(1)|浏览(116)

我正在使用graphql-HTTP包。在操场上没有用于传递令牌(标题)的选项卡。那么如何启用它呢?
我宣布如下

app.use(
      "/graphql",
      graphqlHTTP({
        schema: UserTypes,
        rootValue: UserResolver,
        graphiql: true,
      })
    );
ia2d9nvy

ia2d9nvy1#

首先,graphqlHTTP函数来自express-graphql包,而不是graphql-http包。
使用express-graphql包和graphqlHTTP函数时。您可以使用headerEditorEnabled选项来启用标题编辑器
一个可选的布尔值,当true时启用头编辑器。默认值为false
例如:

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}`);
});

标题编辑器将显示

发送graphql HTTP请求,日志:

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'
}

您可以从req.headers.token访问token标头

相关问题