简体   繁体   中英

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM