Reputation: 45
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())
Upvotes: 0
Views: 58
Reputation: 61
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
Upvotes: 1
Reputation: 4617
You need to add the second frontend as allowed origin, for example if the second fronted is served from http://localhost:3001 do this:
cors({
origin: ["http://localhost:3000", "http://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
Upvotes: 1