简体   繁体   中英

Apollo server set multiple `set-cookie` header in response

I'm using apollo-server-express with apollo-rest-datasources. I'm trying to return multiple set-cookie header in response header to my client from formatResponse method

set-cookie: key1=value1
set-cookie: key2=value2

But the whenever I pass in array it just stringifies it and makes it comma separated This is my formatResponse method

formatResponse: (response, requestContext) => {
    Object.entries(requestContext.context.response.headers).forEach(([key, value]) => {
        requestContext.response.http.headers.set(key, value);
    });

This is my context object

context: ({ req, res }) => {
    return {
      response: {
        headers: {
           'set-cookie': ['key1=value1', 'key2=value2']
       },
      },
      res,
    };
  },

the final response I get is of this form set-cookie: key1=value1, key2=value2 and the browser can't recognise that there are 2 cookies to set and it just sets key1=value1 in cookies.

I use res of express which passed into apollo server context to set multiple cookies. Eg

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

Get the response header from browser:

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

Get cookies by document.cookie :

document.cookie
"key1=value1; key2=value2"

在此处输入图像描述

source code: https://github.com/mrdulin/apollo-graphql-tutorial/tree/master/src/stackoverflow/61183199

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM