res.cookie 不适用于 apollo-server-express
Posted
技术标签:
【中文标题】res.cookie 不适用于 apollo-server-express【英文标题】:res.cookie not working with apollo-server-expres-s- 【发布时间】:2019-08-13 14:31:49 【问题描述】:我一直在尝试将 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;
,
注意:我使用 request-promise-native 来发出请求
我的 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,
);
我尝试过修改选项。我不知道我在这里错过了什么。
【问题讨论】:
【参考方案1】:您可以使用 apollo-server-plugin-http-headers 包在 apollo 服务器中设置 cookie。
在您的解析器中使用就像这样简单:
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
);
【讨论】:
以上是关于res.cookie 不适用于 apollo-server-express的主要内容,如果未能解决你的问题,请参考以下文章
Apollo启动报Config service failed to start in 120 seconds! Please check ./service/apollo-ser
如何从服务器端访问使用 res.cookie 设置的 cookie 到客户端浏览器,现在想要访问它们到服务器端