可以在React中使用GraphQL而不使用Apollo吗?

huangapple go评论72阅读模式
英文:

can i use graphql in react without using Apollo?

问题

我正在尝试在React中使用GraphQL。建议使用Apollo Client来实现应用程序中的GraphQL,但我一开始不想使用它。是否可以在不使用Apollo Client的情况下将GraphQL用于React?

英文:

i am trying to use the GraphQl with react.
suggestions gives that to use apollo client for react to implement the graphql to the application.
but i don't want to use it in the first place.

can i use graphql to react without using apollo client?

答案1

得分: 20

是的,我们可以在不使用Apollo Client的情况下在React中使用GraphQL。我们可以使用fetchaxios,并使事情正常运作。

下面的示例演示了使用fetch来查询GraphQL端点的用法

fetch(<graphql_endpoint>, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ query: '{ posts { title } }' }),
})
.then(res => res.json())
.then(res => console.log(res.data));

使用axios也可以轻松实现相同的效果。希望这对你有所帮助!

英文:

Yes. We can use GraphQL with React without using Apollo Client. We can use fetch or axios and can make things work the same.

Below example demonstrates the usage of fetch to query a GraphQL endpoint.

fetch(&lt;graphql_endpoint&gt;, {
  method: &#39;POST&#39;,
  headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },
  body: JSON.stringify({ query: &#39;{ posts { title } }&#39; }),
})
.then(res =&gt; res.json())
.then(res =&gt; console.log(res.data));

Same thing can be easily achieved using axios. Hope this helps!

答案2

得分: 8

是的,因为GraphQL是一个规范,而不仅仅是一家公司的实现(无论人们如何认为该实现的质量有多好)。在其核心,GraphQL只是一种查询格式和结构化响应。甚至网络调用也不是绝对必要的。

在浏览器中,你也可以跳过Apollo,只需发起一个普通的网络请求。你可以使用XMLHttpRequest或Fetch API轻松进行GraphQL查询的AJAX调用。我认为最简单的方法是安装GraphiQLPlayground,然后在浏览器的开发工具中执行查询。大多数浏览器开发工具的网络选项卡将显示你所需的所有请求标头和URL参数。

Apollo客户端只是为你完成了很多工作,并有一个非常健康的生态系统,可以添加缓存、联合等功能,但没有任何阻止你跳过该库并自己进行HTTP调用的中间人。

英文:

Yes, because GraphQL is a spec rather than just one company's implementation (no matter how good many consider that implementation to be). At its core, GraphQL is just a query format and structured response. Even a network call is not strictly needed.

You could skip Apollo in the browser too, and just invoke a plain web request. You can easily make an AJAX call with XMLHttpRequest or Fetch API to perform the GraphQL query. The easiest way I can think of to work this out is to install GraphiQL or Playground somewhere, open up your browser's developer tools, and execute a query. The Network tab of most browser's developer tools will show you all of the request headers and URL parameters you would need.

The Apollo client just does a lot of that work for you and has a very healthy ecosystem to add caching, federation, etc., but there is nothing stopping you from skipping that library and making the HTTP calls yourself with no middlemen.

huangapple
  • 本文由 发表于 2020年1月7日 02:39:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/59617266.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定