【问题标题】:How to call Graphql Url in Next JS如何在 Next JS 中调用 Graphql Url
【发布时间】:2020-12-22 18:50:09
【问题描述】:

我正在使用 Next Js 构建我的网站 在我的 Index.js 文件中我写的地方

export async function getStaticProps() {
const res = await fetch('https://localhost:3000/api/v1/datas' ,{headers: {"Authorization": "secret","Content-Type" => "application/json"}})
  let data = await res.json()
}

但我想调用 Graphql 而不是这个

{
          "query": "query getDataById($dataId: ID) {
          getDataById(dataId: $dataId) {
          id
          url
         category {
            name
            id
            __typename
          }
        }
      }",
  "variables": {
    "dataId": "123"
  }
}

谁能建议我如何在我的 getStaticProps() 方法中调用 nextjs 中的 Graphql 而不是调用 API。

【问题讨论】:

    标签: graphql next.js vercel


    【解决方案1】:

    我假设你的 GraphQL 后端已经设置好了。所以,剩下的就是 apollo 客户端的设置了。您可以按照以下步骤操作。

    首先安装apollo客户端

    • 纱线添加@apollo/client

    • _app.jsx

    import { ApolloProvider } from '@apollo/client'
    import { ApolloProvider, ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';
    import { setContext } from '@apollo/client/link/context';
    
    
    const httpLink = createHttpLink({
      uri: 'https://localhost:3000/api/v1/datas',
    })
    
    const authLink = setContext((_, { headers }) => {
      // replace this with your secret
      const token = process.env.ACCESS_TOKEN;
      return {
        headers: {
          ...headers,
          authorization: token ? `token ${token}` : "",
        }
      }
    })
    
    const apolloClient = new ApolloClient({
      link: authLink.concat(httpLink),
      cache: new InMemoryCache(),
    })
    
    function MyApp({ Component, pageProps }) {
    
      return <ApolloProvider client={apolloClient}>
        <Component {...pageProps} />
      </ApolloProvider>
    }
    
    export default MyApp
    
    • somepage.jsx
    import { useQuery, gql } from '@apollo/client';
    
    const MyQuery = gql`
    query getDataById($dataId: ID) {
              getDataById(dataId: $dataId) {
              id
              url
             category {
                name
                id
                __typename
              }
            }
          }
    `;
    
    export default function Home() {
      const { loading, error, data } = useQuery(IntroQuery, {
        variables: {
          dataId: '123'
        }
      });
    
      if (loading) {
        return <h1>Loading...</h1>
      }
    
      return (
        <div>
          <pre>
            {JSON.stringify(data, null, 2)}
          </pre>
        </div>
      )
    }
    
    
    • 要更深入地了解上述代码到底在做什么,您可以参考此视频以及整个频道 - Leigh Halliday

    【讨论】:

      猜你喜欢
      • 2022-08-14
      • 1970-01-01
      • 2022-12-13
      • 1970-01-01
      • 1970-01-01
      • 2020-11-24
      • 2022-10-23
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多