【问题标题】:Apollo-Client + Express-Graphql Backend - Session does not persist?Apollo-Client + Express-Graphql 后端 - 会话不持久?
【发布时间】:2020-02-12 05:34:30
【问题描述】:

我想我一定没有得到什么。我正在尝试将我的 apollo 客户端 localhost:8000 连接到我的后端 localhost:4000,客户端和服务器位于不同的域中。我在前端使用 apollo (apollo-boost),在后端使用 express-graphql (不是 (!) apollo-server)。

当我从客户端向服务器发送一些登录数据时,我会收到一个响应:用户对象或错误等。这很好。但是,用户实际上从未在服务器上登录(当我签入 graphiql 并请求用户对象时,它始终为空)。

我不知道这是否是一个 CORS 问题,因为当我在同一个域中同时拥有客户端和服务器时,事情曾经正常工作?

这是客户端代码:

import ApolloClient from "apollo-boost"
import fetch from "isomorphic-fetch"
import { HttpLink } from "apollo-link-http"
import { InMemoryCache } from "apollo-cache-inmemory"

const cache = new InMemoryCache()

const link = new HttpLink({
  // uri: "http://localhost:4000/graphql",
  credentials: "include",
})


export const client = new ApolloClient({
  cache,
  fetch,
  link,
  dataIdFromObject: o => o.id,
  uri: "http://localhost:4000/graphql",
})

服务器上的相关位是:

app.use(
  session({
    resave: true,
    saveUninitialized: true,
    secret: 'whatever',
    cookie: {
      secure: false
    },
    store: new MongoStore({
      url: MONGO_URI,
      autoReconnect: true
    })
  })
);

var corsOptions = {
  origin: 'http://localhost:8000',
  credentials: true
};
app.use(cors(corsOptions));
app.use(passport.initialize());
app.use(passport.session());

// Instruct Express to pass on any request made to the '/graphql' route
// to the GraphQL instance.
app.use(
  '/graphql',
  expressGraphQL({
    schema,
    graphiql: true
  })
);

【问题讨论】:

  • “我不知道这是否是 CORS 问题” — 您是否在浏览器控制台中收到提及 CORS 的错误消息?
  • 没有。这是否意味着 CORS 就可以了?

标签: javascript session-cookies apollo apollo-client


【解决方案1】:

似乎他们的 API 略有变化。 我通过在客户端执行此操作来修复它:

import ApolloClient from "apollo-boost"
import fetch from "isomorphic-fetch"
import { InMemoryCache } from "apollo-cache-inmemory"

const cache = new InMemoryCache()

export const client = new ApolloClient({
  cache,
  fetch,
  link,
  credentials: "include",
  dataIdFromObject: o => o.id,
  uri: "http://localhost:4000/graphql",
})

所以我将credentials: "include", 直接包含在 Apollo 客户端中,而不是在 httpLink 中 - 实际上删除了那个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-20
    • 2019-05-18
    • 2019-01-29
    • 2021-05-04
    • 2018-04-28
    • 1970-01-01
    • 2012-11-20
    • 2012-03-17
    相关资源
    最近更新 更多