首页 > 解决方案 > 使用 GraphQL 和 Apollo 客户端时,我不断收到 json 解析错误

问题描述

我正在为这个项目使用 SWAPI Wrapper。而且我的代码看起来是正确的,但由于某种原因,我JSON Parse error: Unexpected EOF在尝试加载数据时不断收到错误消息。当我在 GraphQL 端点执行以下查询时,它可以工作:

{
  allPeople {
    edges {
      node {
        id
        name
        birthYear
        gender
        homeworld {
          name
        }
        species {
          name
        }
      }
    }
  }
}

...但是当我在我的文件中执行此操作时,我只会收到上面提到的错误。下面是我的代码:

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

import{
  ApolloClient,
  ApolloProvider,
  HttpLink,
  InMemoryCache,
} from '@apollo/client'

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: new HttpLink({
    uri: "https://graphql.org/swapi-graphql",
    useGETForQueries: true,
    fetchOptions: {
      mode: 'no-cors',
    }
  })
})

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

reportWebVitals();


应用程序.js
import './App.css';

import { useQuery, gql } from '@apollo/client';

const ALL_PERSONS = gql`
query {
  allPeople {
    edges {
      node {
        id
        name
        birthYear
        gender
        homeworld {
          name
        }
        species {
          name
        }
      }
    }
  }
}
`;

function App() {
  const { loading, error, data} = useQuery(ALL_PERSONS);

  if (loading){
    return (
      <div>
        Loading...
      </div>
    );
  }
  else if (error){
    return(
      <div>
        <h1>Something went wrong!</h1>
        <p>Name: {error.name}</p>
        <p>Message: {error.message}</p>
        <p>Data: {data}</p>

      </div>
    );
  }
  else{
    return (
      <div className="App">
        <h1>Star Wars API</h1>
        <div>
          {data}
        </div>
      </div>
    );
  }
}

export default App;

任何帮助表示赞赏!我是使用 Apollo 客户端和 GraphQL 的新手

标签: javascriptreactjsgraphqlapollo-client

解决方案


推荐阅读