【发布时间】:2021-06-04 16:10:01
【问题描述】:
我正在调用从我的 nodejs 应用程序发送 OTP 的 api。我需要将该 OTP Api 的响应发送到 Angular 应用程序。
我在 Angular 上的 api 服务如下所示:
sendOtp(params): Observable<any> {
return this.apiService.post("/user/send-otp", params)
}
我在 express 应用上的路由器看起来像这样
this.router.post("/user/send-otp", userController.sendOtpMessage);
userController 中的代码如下所示。
static sendOtpMessage(req, res ,next) {
const phone = req.body.phone;
var http = require("https");
var options = {
"method": "GET",
"hostname": "api.msg91.com",
"port": null,
"path": `/api/v5/otp?mobile=${phone}`,
"headers": {
"content-type": "application/json"
}
};
var callOtpApi = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
// I need to send this data in response to my angular app ==>> body.toString()
});
});
callOtpApi.write();
callOtpApi.end();
}
OTP Api 参考文档:https://docs.msg91.com/p/tf9GTextN/e/B1NUt3C8MY/MSG91
【问题讨论】:
-
您的问题是什么?请注意,您将在回调中覆盖 Express
res变量。重命名其中之一。然后,您可以考虑将 api 调用的响应通过管道传输到 res 以进行 express。 -
谢谢,最重要的是我在将响应发送回 Angular 应用程序时面临的问题。我的问题是如何向 Angular 应用程序发送响应。
-
我认为如果您有 HTTP 请求的回调方法,您将无法发送响应,您可能需要寻找基于承诺的方法 @ds97
-
@ds97 为了将数据发送回 Angular 客户端,您需要调用
.send()方法(参见 docu)。可以在sendOtpMessage函数的res参数上调用此方法。
标签: javascript node.js typescript express