如何通过Axios向GraphQL Mutation传递正则表达式字符串?
问题
在forEach循环中用Axios执行GraphQL mutation时,传递正则表达式字符串作为参数(比如^(http|https)\:\/\/[a-zA-Z0-9\u00C0-\u017F\-\.]+\.[a-zA-Z0-9\u00C0-\u017F\/\.\_\-]+?$或^[^\s]+(\s+[^\s]+)*$),出现解析错误:
[ { message: 'Parse error on ""\""" (error) at [13, 32]', locations: [ [Object] ] } ] [ { message: 'Parse error on ""^"" (error) at [13, 34]', locations: [ [Object] ] } ] [ { message: 'Parse error on ""["" (LBRACKET) at [13, 34]', locations: [ [Object] ] } ]
当前代码:
const createMut = (id, res) => ` mutation { createField(input: { id: "${id}", label: "${res.label}", custom_validation: "${res.custom_validation}", }) { table_field { id label } } } `; const myFunc = (id, result) => { result.data.forEach(d => { axiosFunc({ query: create_fields(id, d) }).then((response) => response); }); }
请问如何正确向GraphQL mutation发送正则表达式值?
解决方法
核心问题:直接用模板字符串插值正则表达式,会让其中的特殊字符(比如
"、[、^等)破坏GraphQL的语法结构,导致解析失败,同时还存在注入风险。最优方案:使用GraphQL变量
把动态参数(包括正则表达式)定义为mutation的变量,而非直接拼进查询字符串。GraphQL会自动处理字符串转义,彻底避免语法错误。修改后的代码示例:
// 定义带变量的mutation模板 const createMut = ` mutation CreateField($id: String!, $label: String!, $customValidation: String!) { createField(input: { id: $id, label: $label, custom_validation: $customValidation }) { table_field { id label } } } `; const myFunc = (id, result) => { result.data.forEach(d => { axiosFunc({ query: createMut, variables: { id: id, label: d.label, customValidation: d.custom_validation // 直接传正则字符串,无需手动转义 } }).then((response) => response); }); }变量方案的优势:
GraphQL变量机制会安全传递字符串参数,自动处理所有特殊字符转义,不会让正则符号破坏查询语法,同时规避了GraphQL注入的安全风险,是官方推荐的参数传递方式。临时替代:手动转义(不推荐)
若暂时无法使用变量,需手动转义正则字符串中的双引号和反斜杠:const escapeGraphQLString = (str) => { return str.replace(/\\/g, '\\\\').replace(/"/g, '\\"'); }; const createMut = (id, res) => ` mutation { createField(input: { id: "${escapeGraphQLString(id)}", label: "${escapeGraphQLString(res.label)}", custom_validation: "${escapeGraphQLString(res.custom_validation)}", }) { table_field { id label } } } `;这种方法容易遗漏特殊字符,仅适合临时场景,优先使用变量方案。
内容的提问来源于stack exchange,提问作者nb_nb_nb
相关产品推荐
相关产品推荐

