首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >graphiQL- Axios中的查询

graphiQL- Axios中的查询
EN

Stack Overflow用户
提问于 2020-05-18 22:04:49
回答 1查看 88关注 0票数 0

GraphiQL中的这个查询非常好用:

代码语言:javascript
复制
{
  getSubContentListing(filter: "{\"contentSection\": \"home\"}") {
    edges {
      node {
        id
        contentSection
        contentTitle
      }
    }
  }
}

但是如果我把它包含在我的Axios查询中:

代码语言:javascript
复制
  let query = {
    query: `query {
      getSubContentListing(
        filter: "{\"contentSection\": \"home\"}") {
        edges {
          node {
            contentSection
            contentTitle
          }
        },
      }
    }`
  }
  axios({
    method: 'post',
    url: '/subcontent?apikey=abcdef',
    data: {
      query: query
    }
  })

ESLint给出错误:错误:不必要的转义字符:\“(无用转义)”

如果我将其构建为一个变量,如下所示:

代码语言:javascript
复制
  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,这是可以的,但查询不起作用。我的错误在哪里?

想要

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-18 22:21:01

您需要转义模板字符串文字中的反斜杠字符:

代码语言:javascript
复制
const queryString = `query {
  getSubContentListing(
    filter: "{\\"contentSection\\": \\"home\\"}") {
#             ^                ^    ^      ^
    edges {
      node {
        contentSection
        contentTitle
      }
    },
  }
}`;

或者,您可以使用JSON.stringify创建该字符串

代码语言:javascript
复制
const filterSearch = "{\"contentSection\": \"home\"}";
const queryString = `query {
  getSubContentListing(
    filter: ${ JSON.stringify(filterSearch) }) {
    edges {
      node {
        contentSection
        contentTitle
      }
    },
  }
}`;

这可以用不同的方式编写:

代码语言:javascript
复制
const filterSearch = "{\"contentSection\": \"home\"}";
const filterSearch = '{"contentSection": "home"}';
const filterSearch = JSON.stringify({contentSection: "home"});

使用变量的方法是一种更舒适的方法,它不必在查询中内联JSON.stringify,而是您的

代码语言:javascript
复制
const filterSearch = JSON.stringify("{'contentSection': 'home'}")

未传入正确的字符串值。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61871410

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档