Я использую res
из express, который перешел в контекст сервера apollo для установки нескольких файлов cookie. Например,
import { ApolloServer, gql } from 'apollo-server-express';
import express from 'express';
const typeDefs = gql`
type Query {
dummy: String!
}
`;
const resolvers = {
Query: {
dummy: () => 'hello world',
},
};
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req, res }) => {
return {
response: {
headers: {
'set-cookie': ['key1=value1', 'key2=value2'],
},
},
res,
};
},
formatResponse: (response, requestContext: any) => {
// not working
// requestContext.response!.http!.headers.set('set-cookie', 'key1=value1');
// requestContext.response!.http!.headers.set('set-cookie', 'key2=value2');
// works fine
requestContext.context.res.set('set-cookie', ['key1=value1', 'key2=value2']);
return response!;
},
});
const app = express();
server.applyMiddleware({ app });
app.get('/', (req, res) => {
res.sendFile('index.html', { root: __dirname });
});
app.listen({ port: 4000 }, () => console.log(`? Server ready at http://localhost:4000${server.graphqlPath}`));
Получить заголовок ответа из браузера:
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: *
set-cookie: key1=value1
set-cookie: key2=value2
Content-Type: application/json; charset=utf-8
Content-Length: 33
ETag: W/"21-wOMEaw/ExA+LOH3PCuP0vilR+4w"
Date: Wed, 22 Apr 2020 05:30:20 GMT
Connection: keep-alive
Получить файлы cookie по document.cookie
:
document.cookie
"key1=value1; key2=value2"
исходный код: https://github.com/mrdulin/apollo-graphql-tutorial/tree/master/src/stackoverflow/61183199