如何在Next JS中调用Graphql Url

时间:2020-09-03 13:59:42

标签: graphql next.js vercel

我正在使用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。

1 个答案:

答案 0 :(得分:0)

我认为您的GraphQL后端已经设置好了。因此,剩下的全部必须是阿波罗客户端的设置。您可以按照以下步骤操作。

首先安装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