简体   繁体   English

如何使用Angular 2正确发送和接收Express API响应

[英]How to Properly Send and Receive Express API Response with Angular 2

Here is how I am receiving a response from an Express API call I am making from my Angular 2 application. 这是我从Angular 2应用程序发出的Express API调用中收到响应的方式。 In my component: 在我的组件中:

this.emailService.sendEmail(this.name, this.email, this.message)
                     .subscribe(
                       (res) => {
                         console.log("Success");
                         this.success = true;
                       },
                       (err) => {
                         console.log("Failure");
                         this.success = false;
                       }
                     );

In my email service sendEmail() function: 在我的电子邮件服务中,sendEmail()函数:

return this.http.post('/api/sendemail', data)
                    .map(res => res.json());

From my Express API, I am sending the email and sending a response like so with the emailjs node module: 通过我的Express API,我正在使用emailjs节点模块发送电子邮件并发送响应:

router.post('/sendemail/', (req, res) => {
...
server.send({
    text: "Sent from " + req.body.name + " message: " + req.body.message + " reply to: " + req.body.email,
    from: "email@gmail.com",
    to:   "email@gmail.com",
    subject: "test"
  }, function(err, message) {
    if (err) {
      console.log(err);
      res.status(500).send("Email failed to send.");
    } else if (message) {
      console.log(message);
      res.status(200).send("Email sent successfully.");
    }
  });
});

The email is being successfully sent every time, and a 200 status code is being returned (I see the response in my console and the Heroku console), but the console logs "Failure" regardless. 每次都会成功发送电子邮件,并返回200状态代码(我在控制台和Heroku控制台中看到了响应),但是无论如何控制台都会记录“失败”。 Am I properly sending the response back to my application? 我是否可以将响应正确发送回我的应用程序?

Change: 更改:

res.status(200).send("Email sent successfully.");

To: 至:

res.status(200).send({message: "Email sent successfully."});

or 要么

res.status(200).json({message: "Email sent successfully."});

or 要么

res.status(200);

Try some thing like this. 尝试这样的事情。

res.status(200).json({
        message: 'Email sent successfully.'
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM