next.js @apollo/client with credentials doens'nt work

6rvt4ljy  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(107)

我使用这段代码来设置我的nextJS应用程序与apollo graphql,
第一个月
但问题是,即使我在后端设置它,我也会得到cors错误。cors错误仅出现在网络选项卡中,而不出现在控制台中。当我不使用credentials选项时,代码可以正常工作。我也试过这个
const httpLink = new HttpLink({uri: 'http://localhost:4000/graphql',credentials: 'include',});const client = new ApolloClient({cache,link: httpLink,});
我已经查阅了文档和所有内容,但它无法与配置中的凭据选项一起工作。

import { print } from 'graphql';

const query = gql`
  query MyQuery { ... }
`;

fetch(uri, {
  method: 'POST',
  headers: {
    accept: '*/*',
    'content-type': 'application/json'
  },
  credentials: 'include',
  body: JSON.stringify({
    query: print(query),
    operationName: 'MyQuery', // replace with the operation name in the query you send
  })
})
  .then(res => res.json())
  .then(result => console.log(result))

字符串
我已经尝试过这种方法来运行查询和这工程。
我试过使用graphql的POST请求,它可以工作,但同一应用程序中的apollo客户端不工作。

qmelpv7a

qmelpv7a1#

根据Apollo文档,您应该将您的cors设置放在这里:阿波罗文档

app.use(
  '/graphql',
  cors({ origin: ['https://www.your-app.example', 'https://studio.apollographql.com'] }),
  json(),
  expressMiddleware(server),
);

字符串
在您的示例中,它应该看起来像这样:

const corsOptions = {
  credentials: true,
  origin: ['http://localhost:3000'],
};

const PORT = process.env.PORT || 4000;
const app = express();

const server = new ApolloServer({
  typeDefs,
  resolvers,
cors: corsOptions
});


如果你使用的是apollo-server-express包,那么它应该看起来像这样:

const app = express();
  const server = new ApolloServer({
    schema,
  });

  await server.start();

  server.applyMiddleware({
    app,
    cors: {
      credentials: true,
      origin: [process.env.ORIGIN as string, "studio.apollographql.com"],
    },
  });


不要忘记在此更改后重新启动服务器。

相关问题