Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

247
Visualizações
React CORS error occurs when integrating with graphQL

Now I'm doing an authentication project to learn how to integrate with the FE and GraphQL to store the refresh token inside the cookies and use the access token to get the information. Unfortunately I was unable to store the refresh token after I clicked the login button and the cors error even i'm following all the details and steps from the official website. Thank you everyone for being attention on it

Server Code

async function startApolloServer() {
  const app = express();
  app.use(cors({
    origin:'*', 
    credentials:true,            //access-control-allow-credentials:true
  }))
  const httpServer = http.createServer(app);

  app.use(cookiesParser());

  app.post("/refresh_token", async (req: Request, res: Response) => {
    console.log(req.cookies);

    const token = req.cookies.jid;

    if (!token) {
      return res.send({ status: false, accessToken: "" });
    }

    let payload: any = null;

    try {
      payload = verify(token, process.env.SECRET_KEY as string);
    } catch (error) {
      return res.send({ status: false, accessToken: "" });
    }

    // token is valid, find user and send back accessToken

    const user: any = await AppDataSource.manager.getRepository(User).findOne({
      where: {
        id: payload.userId,
      },
    });

    if (!user) {
      return res.send({ status: false, accessToken: "" });
    }

    if (user.tokenVersion !== payload.tokenVersion) {
      return res.send({ status: false, accessToken: "" });
    }

    sendRefreshToken(res, createRefreshToken(user));

    return res.send({ status: true, accessToken: createAccessToken(user) });
  });

  const schema = await buildSchema({
    resolvers: [UserQuery, UserMutation],
  });
  await AppDataSource.initialize();

  const server = new ApolloServer({
    schema,
    context: ({ req, res }) => {
      return { req, res };
    },
    csrfPrevention: true,
    plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
  });

  await server.start();

  server.applyMiddleware({ app });
  await new Promise<void>((resolve) =>
    httpServer.listen({ port: 4000 }, resolve)
  );
  console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
}

Frontend Code

const client = new ApolloClient({
  uri: "http://localhost:4000/graphql",
  cache: new InMemoryCache(),
  credentials:'include'
});

Error

Error Image

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Remove * and use

app.use(cors())

If you want to allow to access backend can be accessed from anywhere. Or can use

 var corsOptions = {
     origin: 'http://example.com',
 }

If you allow any specific domain. For more options see the documentation.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda