Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

237
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!