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

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

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

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

我也试过了,但是不管用

app.use(cors())

qvtsj1bj

qvtsj1bj1#

我不认为是服务器端的问题,请按照这段代码从您的appoloclient它的工作e

  1. import {
  2. ApolloClient,
  3. HttpLink,
  4. ApolloLink,
  5. InMemoryCache,
  6. concat,
  7. split,
  8. } from "@apollo/client"
  9. import AsyncStorage from "@react-native-async-storage/async-storage"
  10. import { WebSocketLink } from "@apollo/client/link/ws"
  11. import { SubscriptionClient } from "subscriptions-transport-ws"
  12. import { getMainDefinition } from "@apollo/client/utilities"
  13. let token: string | null = null
  14. const getToken = async () => {
  15. return new Promise(async (resolve) => {
  16. try {
  17. let value = await AsyncStorage.getItem("token")
  18. console.log("token", value)
  19. console.log("Done.")
  20. token = value
  21. resolve(value)
  22. } catch (e) {
  23. // read error
  24. }
  25. })
  26. }
  27. const URL = "a2db-130-193-219-4.ngrok.io"
  28. const httpLink = new HttpLink({
  29. uri: https://${URL}/graphql,
  30. })
  31. const wsLink = new WebSocketLink({
  32. uri: wss://${URL}/graphql,
  33. options: {
  34. reconnect: true,
  35. },
  36. })
  37. getToken()
  38. const authMiddleware = new ApolloLink((operation, forward) => {
  39. // add the authorization to the headers
  40. operation.setContext({
  41. headers: {
  42. authorization: ${token || ""},
  43. "Content-Type": "application/json",
  44. },
  45. })
  46. return forward(operation)
  47. })
  48. const splitLink = split(
  49. ({ query }) => {
  50. const definition = getMainDefinition(query)
  51. return (
  52. definition.kind === "OperationDefinition" &&
  53. definition.operation === "subscription"
  54. )
  55. },
  56. wsLink,
  57. httpLink
  58. )
  59. const client = new ApolloClient({
  60. cache: new InMemoryCache(),
  61. link: concat(authMiddleware, splitLink),
  62. })
  63. export default client

字符串

展开查看全部
cuxqih21

cuxqih212#

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

  1. cors({
  2. origin: ["http://localhost:3000", "http://localhost:3001"],
  3. credentials: true
  4. })

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

相关问题