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

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


0

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: "https://localhost:3000",
credentials: true,
})
);

also, I try but is doesn’t work

app.use(cors())

2 Answers
2


1

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


1

You need to add the second frontend as allowed origin, for example if the second fronted is served from https://localhost:3001 do this:

cors({ 
  origin: ["https://localhost:3000", "https://localhost:3001"], 
  credentials: true
})

If you want to allow all origins you can set origin: true.

Look here for all the allowed options for origin:
https://www.npmjs.com/package/cors#configuration-options

2

  • I try it but it doesn't work, I try another project it works it means my back end does not return data for only one front-end why? I don't now

    – rebaz omar

    Mar 15, 2022 at 11:40

  • @rebazomar We need more details, can you post the error you get in the browser console and the requests that fail from the network tab?

    – Andrei

    Mar 17, 2022 at 13:23



Leave a Reply

Your email address will not be published. Required fields are marked *