如何使用Apollo Client查询Yelp GraphQL API时解决身份验证错误

问题描述 投票:0回答:1

我正在尝试创建一个使用Apollo Client查询Yelp GraphQL API的基本React应用。

[当我尝试发送查询时,我收到401错误响应。

我已经与Yelp一起加入了开发人员Beta程序,并尝试刷新我的API密钥,但这没有用。这是我的index.js文件的代码。

import React from 'react'
import ReactDOM from 'react-dom'
import {ApolloProvider} from 'react-apollo'
import { ApolloClient } from "apollo-client";
import { createHttpLink } from "apollo-link-http";
import { setContext } from "apollo-link-context";
import { InMemoryCache } from "apollo-cache-inmemory";
import './index.css'
import App from './App'
import registerServiceWorker from './registerServiceWorker'

const httpLink = createHttpLink({
  uri: "https://api.yelp.com/v3/graphql",
  fetchOptions: {
    mode: "no-cors"
  }
});

const authLink = setContext((_, { headers }) => {
  const token = process.env.yelpApiKey;
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
      "Content-Type": "application/graphql"
    }
  };
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

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

我在这里想念什么吗?任何建议表示赞赏!

谢谢!

reactjs graphql apollo-client yelp
1个回答
0
投票

我有同样的问题,到目前为止,我认为这里的问题是Yelp不支持CORS,甚至我们使用no-cors也无济于事。您可以查看以下讨论。

GraphQL api returns 500 for a valid query #248

WKWebView CORS error #44

我是YELP API的新手,我对Apollo Client的经验还不是很丰富。但是我的工作方法如下。我不会将此项目仅用于生产目的。我用herokuapp激活了cors。

const cache = new InMemoryCache();
// Seting up Apollo Client
const client = new ApolloClient({
  uri: 'https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/graphql',
  request: (operation) => {
    operation.setContext({
      headers: {
        Authorization: `Bearer ${apiKey}`,
        'Accept-Language': 'en-US',
      },
    });
  },
  cache,
});

Status Code: 200 OK

在此解决方案中,我必须使用'Accept-Language': 'en-US',,因为如果没有此操作,我将收到一个错误400 Bad request,甚至en-us是默认的;]

code: "INVALID_LOCALE"
description: "The locale you specified is not valid."

也许您注意到我没有指定

“ Content-Type”:“ application / graphql”

那是因为这又给我们带来了400个错误的请求。 Apollo Client默认值的内容类型为“ application / json”,当我们指定“ application / graphql”时,此设置将被覆盖。您可以在下面阅读有关该内容的有用讨论。

Getting 400 error "Must Provide Query String" from Yelp GraphQL API (using Apollo Client) #278

也可以在下面的屏幕截图中查看,

Status Code: 400 Bad Request

我希望这对某人有帮助,我知道可能会有更好的解决方案,如果我对此有所改进,我会告诉您。

© www.soinside.com 2019 - 2024. All rights reserved.