模板文字-从API获取错误 [英] Template literal - getting error from 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 )"
第二个当我搜索单个单词时-字段" media自变量" search要求类型为String,找到火影忍者."
Second when i search for single word - "Field "media" argument "search" requires type String, found naruto."
这是什么问题?
您可以在此处看到完整的代码- https://github.com/red4211/react-动漫搜索,将应用程序部署到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屋!