You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SendGrid API搜索联系人时如何将查询中的固定邮箱替换为变量

问题原因

你直接将变量名写入查询字符串常量时,JavaScript不会将其解析为对应变量值,只会作为普通文本处理,因此查询逻辑无法生效。

正确实现方案

推荐使用ES6模板字符串实现变量插值,写法更简洁易读,修改后的完整代码如下:

var request = require("request");
// 先获取邮箱变量
const email = req.user.email;
// 可选:转义邮箱中的单引号,避免破坏查询语法,防范注入风险
const escapedEmail = email.replace(/'/g, "''");

var options = { 
  method: 'POST',
  url: 'https://api.sendgrid.com/v3/marketing/contacts/search',
  headers: { 
    'content-type': 'application/json',
    authorization: 'Bearer SG.key' 
  },
  // 用反引号包裹模板字符串,通过${}插入变量
  body: { query: `email LIKE '${escapedEmail}' AND CONTAINS(list_ids, '6bcc2d0c-ea17-41ba-a4a1-962badsasdas1')` },
  json: true 
};

request(options, function (error, response, body) {
  if (error) throw new Error(error);
  console.log(body);
});

如果你的运行环境不支持ES6语法,也可以用传统字符串拼接的方式实现:

body: { query: "email LIKE '" + escapedEmail + "' AND CONTAINS(list_ids, '6bcc2d0c-ea17-41ba-a4a1-962badsasdas1')" }

内容的提问来源于stack exchange,提问作者AndrewLeonardi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 19:39:01