【问题标题】:What's proper way of escaping input string in JavaScript?在 JavaScript 中转义输入字符串的正确方法是什么?
【发布时间】:2018-03-24 12:55:13
【问题描述】:

查看带有 JavaScript 变量注入的 graphql 突变(请忽略它是手动构建的,而不是通过一些 gql 助手)

mutation {
  createPost(
    name: "${name}",
    description: "${description}" 
  ) { id }
}

转义namedescription字符串变量有什么标准函数吗?

例如。一些函数gqlEscape 将使查询安全:

mutation {
  createPost(
    name: "${gqlEscape(name)}",
    description: "${gqlEscape(description)}" 
  ) { id }
}

这个函数会是什么样子?

【问题讨论】:

    标签: javascript string escaping graphql graphql-js


    【解决方案1】:

    您可以使用专为您的用例设计的 GraphQL 变量,而不是进行字符串插值。您也可以使用原始 HTTP 来执行此操作,但在这种情况下,我通常使用 graphql-request

    这是一个例子:

    import { request } from 'graphql-request'
    
    const mutation = `
      mutation newPost($name: String!, $description: String) {
        createPost(
          name: $name,
          description: $description 
        ) {
          id
        }
      }
    `
    
    const variables = {
      name: 'New Post',
    }
    
    request('my-endpoint', mutation, variables).then(data => console.log(data))
    

    几点说明:

    • 我定义了两个变量,name: String!description: StringString! 表示,它是一个字符串类型的必需 变量,而String 表示它是一个可选变量。您可以看到我没有为description 传递值,这是可能的,因为它是可选的。
    • 我确实没有为两个字符串指定双引号,这已经由 GraphQL 变量本身处理了。
    • 您可以阅读有关 GraphQL 变量herehere 的更多信息。

    【讨论】:

    • 谢谢,看起来 GraphQL 请求库完成了这项工作。我只是好奇它是如何在内部工作的-但是在查看 graphql-request 代码时,只使用了 JSON.stringify ..所以可能在我最初的示例中,它可能可以运行 name: ${JSON.stringify(name)}, 并且它可能只是工作.. / / 但你是对的,这不是真正正确的做法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-07
    • 2018-09-01
    • 1970-01-01
    相关资源
    最近更新 更多