Подписка на мой сервер Apollo не работает: не удается прочитать заголовки свойств undefined

Я попытался использовать его с контекстным подключением и добавить параметры подписки на сервер Apollo, но это не сработало. Я впервые использую серверные подписки Apollo, и я не знаю, в конфигурации сервера или в резолверах ошибка. У меня нет проблем с запросом или мутацией, проблема в подписке.

Это мой index.js:

    import express from 'express';
    import { createServer } from 'http';
    import { ApolloServer } from 'apollo-server-express';
    import { typeDefs } from './data/schema';
    import { resolvers } from './data/resolvers';
    import cors from 'cors';
    import jwt from 'jsonwebtoken';

    const bodyParser = require('body-parser');
    const PORT = process.env.PORT ||  4004;
    const app = express();

    app.use(bodyParser.json());
    app.use(cors());

    const server = new ApolloServer({
          typeDefs,
          resolvers,
          context: async({req, connection}) => {
            console.log("Context connection", connection)  
            const token = req.headers['authorization'];
              if(connection){
                return connection.context;
              } else {
                if(token !== "null"){
                    try{

                      //validate user in client.
                      const currentUser = await jwt.verify(token, process.env.SECRET);

              //add user to request
              req.currentUser = currentUser;

              return {
                  currentUser
              }   
            }catch(err){
                return "";
            }

      }

    } 

  },
  subscriptions: {
    path: "/subscriptions",
    onConnect: async (connectionParams, webSocket, context) => {
      console.log(`Subscription client connected using Apollo server's built-in SubscriptionServer.`)
    },
    onDisconnect: async (webSocket, context) => {
      console.log(`Subscription client disconnected.`)
    }
   }

});

    server.applyMiddleware({app});

    const httpServer = createServer(app);
    server.installSubscriptionHandlers(httpServer);

    httpServer.listen({ port: PORT }, () =>{
      console.log(`???? Server ready at 
      http://localhost:${PORT}${server.graphqlPath}`)
      console.log(`???? Subscriptions ready at 
    ws://localhost:${PORT}${server.subscriptionsPath}`)
    })

С детской площадки

Моя мутация:

    mutation {
      pushNotification(label:"My septh notification") {
        label
      }
    }

Мой запрос:

    query {
      notifications {
        label
      }
    }

Моя подписка:

    subscription {
      newNotification {
        label
      }
    }

Ошибка:

{
       "error": {
         "message": "Cannot read property 'headers' of undefined"
        }
 }

person Brian Nieto    schedule 06.09.2019    source источник


Ответы (3)


Я решаю это просто так:

const server = new ApolloServer({
      typeDefs,
      resolvers,
      context: async ({ req, connection }) => {
        if (connection) {
         // check connection for metadata
         return connection.context;
        } else {
         // check from req
         const token = req.headers.authorization


        if(token !== "null"){
          try{

          //validate user in client.
          const currentUser = await jwt.verify(token, process.env.SECRET);

          //add user to request
          req.currentUser = currentUser;

          return {
              currentUser
          }   
        }catch(err){
            return "";
                }
             }

         }
       },


    });
person Brian Nieto    schedule 06.09.2019

Проблема в том, что в вашей строке

const token = req.headers['authorization'];

Переменная req будет неопределенной для соединений WebSocket. Для их аутентификации см. https://www.apollographql.com/docs/graphql-subscriptions/authentication/

person Coxer    schedule 06.09.2019
comment
Я прочитал документацию, но не знаю, как это реализовать с помощью токена jwt. Если у вас есть какие-либо ресурсы, которыми вы можете поделиться со мной, я был бы признателен. Спасибо - person Brian Nieto; 06.09.2019

Вы можете проверить токен jwt при обратном вызове контекста

server = new ApolloServer({
  schema: schema ,
  graphiql: true ,
  context:({req, connection} )=>
    if connection
      token = connection.context["x-access-token"]
      decoded = await LoginService.verify token #verify by jwt

      if decoded == null
        throw new Error("auth required")
      return connection.context
    headers = req.headers
    token = headers["x-access-token"]
    decoded = await LoginService.verify token #verify by jwt
    return authed: decoded != null
})
person matinekonya    schedule 20.11.2019