gpt4 book ai didi

express - res.cookie 不适用于 apollo-server-express

转载 作者:行者123 更新时间:2023-12-03 19:30:32 24 4
gpt4 key购买 nike

我一直在尝试从服务器向客户端发送一个 cookie。我获得了响应数据,但在响应 header 中没有看到“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,
});

我试过修改选项。我不知道我在这里错过了什么。

最佳答案

您可以使用 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
}
});

关于express - res.cookie 不适用于 apollo-server-express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55302412/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com