【问题标题】:I get Newwork error: Failed to fetch every time in apollo client我收到 Newwork 错误:每次在 apollo 客户端中都无法获取
【发布时间】:2020-10-31 14:55:38
【问题描述】:

这是我的 App.js 文件。我在这里运行我的查询。
我使用 apollo 客户端而不是 apollo-boost。

import React, { useEffect } from "react";
import { useQuery } from "react-apollo";
import gql from "graphql-tag";
    
const MY_QUERY = gql`
  query {
    getAllSalons {
      id
      displayName
      email
    }
  }
`;
        
const App = (props) => {
  const { data, loading, error } = useQuery(MY_QUERY);
  useEffect(() => console.log("-------", data), [data]);
  useEffect(() => console.log("-------", error), [error]);
  return (
    <div className="App">
      <h1>KOMB COLLECTION</h1>
      {loading ? <h2>Loading...</h2> : <h2>Data :)</h2>}
    </div>
  );
}

这是我在 index.js 文件中设置 apollo 客户端的方法
我在我的 apollo 客户端中设置了身份验证。

这里是所有的导入

import ApolloClient from "apollo-client";
import { ApolloProvider } from "react-apollo";
import { createHttpLink } from "apollo-link-http";
import { setContext } from "apollo-link-context";
import { InMemoryCache } from "apollo-cache-inmemory";

我无法仅使用此端点获取错误,但它可以工作 在 Postman 中很好,另一个端点可以很好地与此代码配合使用。

const httpLink = createHttpLink({
  uri: "http://13.125.142.93:3001/graphql",
});

const authLink = setContext((_, { headers }) => {
  const token = localStorage.getItem("token");
  return {
    headers: {
      ...headers,
      Authorization: token ? token : "",
    },
  };
});
const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(),
});

ReactDOM.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  document.getElementById("root")
);

我是 graphql 的新手,不知道如何处理这个错误。此外,我找不到任何相关文档。

我在控制台上收到此错误

Access to fetch at 'http://13.125.142.93:3001/graphql' from origin
'http://localhost:3000' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.

【问题讨论】:

标签: apollo apollo-client


【解决方案1】:

出现此错误是因为后端没有 cors 的配置。在您的后端配置 cors,一切都会正常工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-11
    • 2021-02-04
    • 1970-01-01
    • 2022-11-01
    • 2021-12-01
    • 2023-03-18
    • 2018-09-18
    • 2020-05-14
    相关资源
    最近更新 更多