Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

238
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda