如何将Node.js Express中OTP接口的响应返回给Angular前端应用
实现方案
核心修改说明
你当前代码的核心问题是第三方接口请求的回调参数和Express的响应对象重名,导致无法调用Express的响应方法返回数据,按以下步骤修改即可:
步骤1:修正变量命名冲突&添加错误处理
将第三方请求的回调响应参数重命名避免和Express的res冲突,同时添加请求错误监听防止无响应。
步骤2:转发OTP接口响应到Angular
在OTP接口响应结束的end事件中,直接调用Express的res对象将数据返回给前端即可。
修改后的完整sendOtpMessage代码
static sendOtpMessage(req, res, next) { const phone = req.body.phone; const http = require("https"); // 注意:请按照msg91接口要求,在path中补充你的authkey参数,否则接口会调用失败 const options = { "method": "GET", "hostname": "api.msg91.com", "port": null, // 对手机号做编码处理避免特殊字符异常 "path": `/api/v5/otp?mobile=${encodeURIComponent(phone)}&authkey=替换为你自己的msg91授权key`, "headers": { "content-type": "application/json" } }; const callOtpApi = http.request(options, function (otpRes) { // 这里把res改成otpRes,避免和外层Express的res冲突 const chunks = []; otpRes.on("data", function (chunk) { chunks.push(chunk); }); otpRes.on("end", function () { const body = Buffer.concat(chunks).toString(); console.log('OTP接口返回:', body); // 直接将OTP接口响应返回给Angular前端 res.json({ success: true, data: JSON.parse(body) }); }); }); // 监听第三方接口调用错误 callOtpApi.on('error', function (err) { console.error('调用OTP接口失败:', err); res.status(500).json({ success: false, message: '发送验证码失败' }); }); callOtpApi.write(); callOtpApi.end(); }
前端适配说明
你现有的Angular侧代码无需修改,调用sendOtp方法后直接订阅Observable即可拿到后端返回的OTP接口响应数据:
// 前端调用示例 this.xxxService.sendOtp({phone: '目标手机号'}).subscribe(res => { console.log('收到后端返回的OTP响应:', res); // 后续业务逻辑处理 })
内容的提问来源于stack exchange,提问作者ds97
相关产品推荐
相关产品推荐

