【问题标题】:Can't make correct GraphQL query to Yelp无法对 Yelp 进行正确的 GraphQL 查询
【发布时间】:2019-01-01 13:25:44
【问题描述】:

也许这件事很明显,但我是 Apollo 的新手。 我正在尝试向 yelp 服务器发送一个简单的 graphQL 查询

import React from 'react';
import { render } from 'react-dom';
import ApolloClient from 'apollo-boost';
import { setContext } from 'apollo-link-context';
import { createHttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import gql from 'graphql-tag';
import { ApolloProvider } from 'react-apollo';
import { yelpCredentials } from '../../../keys/yelp/config';
import 'cross-fetch/polyfill';
import App from './components/App';

const httpLink = createHttpLink({
  uri: 'https://api.yelp.com/v3/graphql',
});
const authLink = setContext((_, { headers }) => {
  const token = yelpCredentials.API_Key;
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : '',
      'Content-Type': 'application/graphql',
    },
  };
});
const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(),
});

client.query(
 ***[QUERY_CONTENT]***
 ,
}).then(console.log);

render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  document.getElementById('app'),
);

试过了: 查询1:

client.query({
  query: gql`
  query business($id: String!) {
      business(id: $id) {
        name
        id
        alias
        rating
        url
      }
    }
  `,
  variables: { id: 'garaje-san-francisco' },
}).then(console.log);

错误:未捕获(在承诺中)错误:网络错误:意外的令牌

查询2:

client.query({
  query: gql`
      query business(id: "garaje-san-francisco") {
        name
        id
        alias
        rating
        url
      }
    }
  `,
}).then(console.log);

错误:“语法错误:应为 $,找到名称“id””

查询3:

 client.query({
  query: gql`
    query business($id: String!) {
      name
      id
      alias
      rating
      url
    }
  `,
  variables: {
    id: 'garaje-san-francisco',
  },
}).then(console.log);

错误:未捕获(在承诺中)错误:网络错误:意外的令牌

我正在通过邮递员 https://imgur.com/hoC7s5e 获取数据

【问题讨论】:

  • 您是否在请求中使用 'Content-Type': 'application/json' -header?
  • 身份验证可能存在问题,这就是为什么 yelp 可能会返回 HTML 而不是 JSON,而 Apollo 无法解析它。有没有试过console.logsetContext返回的对象,看起来不错?

标签: reactjs api graphql apollo yelp


【解决方案1】:

从“apollo-boost”导入 ApolloClient;

我试图将 apollo-client 客户端的配置应用到 apollo-boost 客户端

【讨论】:

    猜你喜欢
    • 2022-09-24
    • 2020-09-24
    • 1970-01-01
    • 2018-06-28
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 2021-01-26
    相关资源
    最近更新 更多