Search code examples
node.jsexpressgraphqlcors

why i can't connect with my api , the header of requset is (blocked by cors) nodejs


I want to return data from my graphql API, I have two front-end in one of these is work, but in another front-end, it doesn't work

when I run the first front end in this port it works but for the second one to doesn't work and it says blocked by cors policy

hare is my back end code

import cors from "cors"; app.use( cors({ origin: "http://localhost:3000", credentials: true, }) );

also, I try but is doesn't work

app.use(cors())


Solution

  • i don't think is server-side problem please follow this code from your appoloclient it work for e

    import {
      ApolloClient,
      HttpLink,
      ApolloLink,
      InMemoryCache,
      concat,
      split,
    } from "@apollo/client"
    import AsyncStorage from "@react-native-async-storage/async-storage"
    
    import { WebSocketLink } from "@apollo/client/link/ws"
    import { SubscriptionClient } from "subscriptions-transport-ws"
    import { getMainDefinition } from "@apollo/client/utilities"
    
    let token: string | null = null
    
    const getToken = async () => {
      return new Promise(async (resolve) => {
        try {
          let value = await AsyncStorage.getItem("token")
          console.log("token", value)
          console.log("Done.")
          token = value
          resolve(value)
        } catch (e) {
          // read error
        }
      })
    }
    
    const URL = "a2db-130-193-219-4.ngrok.io"
    
    const httpLink = new HttpLink({
      uri: https://${URL}/graphql,
    })
    
    const wsLink = new WebSocketLink({
      uri: wss://${URL}/graphql,
      options: {
        reconnect: true,
      },
    })
    
    getToken()
    
    const authMiddleware = new ApolloLink((operation, forward) => {
      // add the authorization to the headers
      operation.setContext({
        headers: {
          authorization: ${token || ""},
          "Content-Type": "application/json",
        },
      })
    
      return forward(operation)
    })
    
    const splitLink = split(
      ({ query }) => {
        const definition = getMainDefinition(query)
        return (
          definition.kind === "OperationDefinition" &&
          definition.operation === "subscription"
        )
      },
      wsLink,
      httpLink
    )
    
    const client = new ApolloClient({
      cache: new InMemoryCache(),
      link: concat(authMiddleware, splitLink),
    })
    
    export default client