模板文字 - 从 API 获取错误 [英] Template literal - getting error from API

查看:13
本文介绍了模板文字 - 从 API 获取错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个按名称搜索动漫的方法,API 是 graphQL.这是查询的重要部分

So i have a method that searches for anime by name, API is graphQL. Here's the important part of the query

const searchQuery = this.state.searchString;

var query = `query Search{
  # the rest of the query omitted for brevity
    media(type:ANIME, search: ${searchQuery} ){
  # ... 
}
`

我收到两种类型的错误响应,第一种是当搜索字符串由多个由空格分隔的单词组成时 - 语法错误:预期:,找到)"

I'm getting two types of errors in response, first is when search string consists of multiple words separated by spaces - "Syntax Error: Expected :, found )"

第二个当我搜索单个单词时 - 字段媒体"参数搜索"需要类型字符串,找到火影忍者."

Second when i search for single word - "Field "media" argument "search" requires type String, found naruto."

这里有什么问题?

你可以在这里看到完整的代码 - https://github.com/red4211/react-Anime-search ,应用程序部署到 github 页面,搜索 API 响应转到控制台 - https://red4211.github.io/react-anime-search/

You can see full code here - https://github.com/red4211/react-anime-search , app deployed to github pages, search API response goes to console - https://red4211.github.io/react-anime-search/

推荐答案

问题是,给定一些像火影忍者"这样的查询,您当前的代码会产生以下文本:

The issue is that given some query like "naruto", your current code results in the following text:

media(type:ANIME, search: naruto ) {

这不是有效的语法,因为字符串文字应该用双引号 (") 括起来.

This is not valid syntax since String literals should be surrounded by double quotes (").

不要使用字符串插值向查询提供动态值.这些应始终表示为 变量 并作为请求中的单独对象与 query 一起.

Don't use string interpolation to provide dynamic values to the query. These should always be expressed as variables and included as a separate object inside your request alongside query.

您需要将变量定义为操作的一部分,提供适当的类型

You need to define the variable as part of your operation, providing the appropriate type

var query = `query Search ($searchQuery: String!) {

然后你可以在操作中的任何地方使用该变量:

then you can use the variable anywhere inside the operation:

media(type:ANIME, search: $searchQuery) {

现在只需将变量值与您的请求一起传递即可.

Now just pass the variable value along with your request.

body: JSON.stringify({
  query,
  variables: {
    searchQuery,
  }
})

请注意,在 GraphQL 文档中,变量名称以 $ 为前缀,但在它之外,我们不这样做.

Note that the variable name is prefixed with a $ inside the GraphQL document, but outside of it, we don't do that.

这篇关于模板文字 - 从 API 获取错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆