GraphiQL中的这个查询非常好用:
{
getSubContentListing(filter: "{\"contentSection\": \"home\"}") {
edges {
node {
id
contentSection
contentTitle
}
}
}
}但是如果我把它包含在我的Axios查询中:
let query = {
query: `query {
getSubContentListing(
filter: "{\"contentSection\": \"home\"}") {
edges {
node {
contentSection
contentTitle
}
},
}
}`
}
axios({
method: 'post',
url: '/subcontent?apikey=abcdef',
data: {
query: query
}
})ESLint给出错误:错误:不必要的转义字符:\“(无用转义)”
如果我将其构建为一个变量,如下所示:
let query = {
query: `query($filterSearch: String) {
getSubContentListing(
filter: $filterSearch) {
edges {
node {
contentSection
contentTitle
}
},
}
}`
}
axios({
method: 'post',
url: '/subcontent?apikey=abcdef',
data: {
query: query,
variables: {
filterSearch: JSON.stringify("{'contentSection': 'home'}")
}
}
})对于ESLint,这是可以的,但查询不起作用。我的错误在哪里?
想要
发布于 2020-05-18 22:21:01
您需要转义模板字符串文字中的反斜杠字符:
const queryString = `query {
getSubContentListing(
filter: "{\\"contentSection\\": \\"home\\"}") {
# ^ ^ ^ ^
edges {
node {
contentSection
contentTitle
}
},
}
}`;或者,您可以使用JSON.stringify创建该字符串
const filterSearch = "{\"contentSection\": \"home\"}";
const queryString = `query {
getSubContentListing(
filter: ${ JSON.stringify(filterSearch) }) {
edges {
node {
contentSection
contentTitle
}
},
}
}`;这可以用不同的方式编写:
const filterSearch = "{\"contentSection\": \"home\"}";
const filterSearch = '{"contentSection": "home"}';
const filterSearch = JSON.stringify({contentSection: "home"});使用变量的方法是一种更舒适的方法,它不必在查询中内联JSON.stringify,而是您的
const filterSearch = JSON.stringify("{'contentSection': 'home'}")未传入正确的字符串值。
https://stackoverflow.com/questions/61871410
复制相似问题