res.cookie не работает с apollo-server-express

Я пытался отправить клиенту файл cookie с сервера. Я получаю данные ответа, но не вижу "set-cookie" в заголовках ответа

Конфигурация моего сервера Apollo:

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req, connection, res }) => ({
    dummyModels: dummyModels,
    models: models,
    req,
    connection,
    res,
    currentUser: dummyModels.users[2],
    dummyUsers: dummyModels.dummyUsers,
  }),
});

app.use(cors({
  credentials: true,
  origin: 'http://localhost:3000',  
  // preflightContinue: true,
}));

Мой решатель:

login: async (parent, args, context) => {
      const _include_headers = function(body, response, resolveWithFullResponse) {
        return {'headers': response.headers, 'data': body};
      };

      const loginRequestOptions = {
        method: 'POST',
        uri: 'http://localhost:3000/incorta/authservice/login',
        qs: {
          // access_token: 'xxxxx xxxxx', // -> uri + '?access_token=xxxxx%20xxxxx'
          user: args.input.username,
          pass: args.input.password,
          tenant: args.input.tenantName,
        },
        transform: _include_headers,
        json: true // Automatically parses the JSON string in the response
      };

      const loginResponse = await request(loginRequestOptions);
      console.log(loginResponse);

      context.res.cookie(
        'JSESSIONID',
        tough.Cookie.parse(loginResponse.headers['set-cookie'][0]).value,
        {
          // expires  : new Date(Date.now() + 9999999),
          // path: '/incorta/',
          // HttpOnly: false,
          // maxAge: 1000 * 60 * 60 * 24 * 99, // 99 days
        },
      );
      context.res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

      return loginResponse.data;
    },

Примечание: я использую запрос-обещание-нативный, чтобы сделать запрос

Конфигурация клиента My Apollo:

const httpLink = createHttpLink({
  uri: 'http://172.16.16.130:4000/graphql',
  credentials: 'include',
  fetchOptions: {
    credentials: 'include',
  },
});

const wsLink = new WebSocketLink({
  uri: 'ws://172.16.16.130:4000/graphql',
  options: {
    reconnect: true,
    connectionParams: {
      headers: {
        'x-user-header': localStorage.getItem('userObject'),
      },
    },
  }
});

const terminatingLink = split(
  // split based on operation type
  ({ query }) => {
    const { kind, operation } = getMainDefinition(query);
    return kind === 'OperationDefinition' && operation === 'subscription';
  },
  wsLink,
  httpLink,
);

const link = ApolloLink.from([terminatingLink]);

const cache = new InMemoryCache();

export const client = new ApolloClient({
    link,
    cache,
});

Я пробовал повозиться с вариантами. Я не знаю, что мне здесь не хватает.


person BahaaZidan    schedule 22.03.2019    source источник


Ответы (1)


Вы можете использовать https://www.npmjs.com/package/apollo-server-plugin-http-headers пакет для установки куки на сервере apollo.

Использование внутри ваших преобразователей очень просто:

context.setCookies.push({
    name: "cookieName",
    value: "cookieContent",
    options: {
        domain: "example.com",
        expires: new Date("2021-01-01T00:00:00"),
        httpOnly: true,
        maxAge: 3600,
        path: "/",
        sameSite: true,
        secure: true
    }
});
person b2a3e8    schedule 16.01.2020