为什么我不能用我的API连接,requset的头是(被cors阻止)nodejs

7uzetpgm  于 2023-11-17  发布在  Node.js
关注(0)|答案(2)|浏览(133)

我想从我的graphql API返回数据,我有两个前端,其中一个是工作,但在另一个前端,它不工作
当我在这个端口运行第一个前端时,它工作,但第二个不工作,它说被cors策略阻止
Hare是我的后端代码

*从“cors”导入cors;app.use(cors({ origin:“http://localhost:3000”,credentials:true,}));

我也试过了,但是不管用

app.use(cors())

qvtsj1bj

qvtsj1bj1#

我不认为是服务器端的问题,请按照这段代码从您的appoloclient它的工作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

字符串

cuxqih21

cuxqih212#

您需要添加第二个前端作为允许的来源,例如,如果第二个前端是从http://localhost:3001提供的,请执行以下操作:

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

字符串
如果你想允许所有的原点,你可以设置origin: true
在这里查看所有允许的origin选项:
https://www.npmjs.com/package/cors#configuration-options

相关问题