node.js - 如何在 Angular 4 Universal 中发出 http post 请求?

标签 node.js angular express nodemailer angular-universal

我正在开发Angular 4 Universal,我正在尝试使用nodemailer发送联系表单的电子邮件。我无法通过 http.post

发布数据

contact.template.html

<form (ngSubmit)="onSubmit()">
      <input type="text" name="fullname"  (keyup)="validate()" [class.requireds]="isNameInvalid"  placeholder="Full Name" required [(ngModel)]="contactObj.userName" />
      <input type="text" name="email" (keyup)="validate()"  [class.requireds]="isEmailInvalid" placeholder="Email" required  [(ngModel)]="contactObj.userEmail"/>
  </form>

contact.component.ts

contactObj = {
userName: "",
userEmail: "",
};


onSubmit() {
   if (this.isNameInvalid || this.isEmailInvalid) {
   return;
  } else {

    let params = JSON.stringify(this.contactObj);
    let headers = new Headers({"Content-Type": "application/json"});
    let options = new RequestOptions({headers: headers});
    this.http.post("/api/send", params, options).subscribe(res => {
    });
  }
}

server.ts

import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import 'rxjs/Rx';
import * as express from 'express';
import * as compression from 'compression';
import { platformServer, renderModuleFactory } from '@angular/platform-server';
import { ServerAppModule } from './app/server-app.module';
import { ngExpressEngine } from './modules/ng-express-engine/express-engine';
import { ROUTES } from './routes';


const app = express();
const port = Number(process.env.PORT || 8080);

app.engine('html', ngExpressEngine({
  bootstrap: ServerAppModule
}));

app.set('view engine', 'html');
app.set('views', 'src');

app.post("/api/send", sendMailApi);

app.use(compression());
app.use('',express.static('dist'));    
app.use('/assets',express.static('dist/assets'));

app.use('/static',express.static('dist/static', {
  index: false
}));

app.listen(port,() => {
    console.log(`Listening at ${port}`);
});

api.ts

// For send Mail
export function sendMailApi(req, res) {
 console.log(req.body.userName); //returns undefined

let mailTo = {

 from: '"Contact Us" <<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fb9d9494bb9d9494d5989496" rel="noreferrer noopener nofollow">[email protected]</a>>',
 to: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f6949e83859e9798d8909999b6909999d895999b" rel="noreferrer noopener nofollow">[email protected]</a>",
 subject: "Foo- Reach out to us",
 html: "Message Body:<p>my message goes here</p>",
 replyTo: req.body.userEmail
};

let smtpTransport = nodemailer.createTransport({
 host: "smtp.gmail.com",
 port: 465,
 secure: true,
 auth: {
  user: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94f2fbfbd4f2fbfbbaf7fbf9" rel="noreferrer noopener nofollow">[email protected]</a>",
  pass: "foo@foo"
 }
});

smtpTransport.sendMail(mailTo, function (error, info) {
  if (error) {
   console.log("Error sending mail: %s", error);
  } else {

   console.log("Message sent: " + info.messageId, info.response);
   //res.message = response.message;
  }
 });

}

api.ts中,我收到的所有值都是未定义的。 我的代码有什么问题吗?

谢谢。

最佳答案

您的服务器端代码中缺少 bodyParser。 执行以下操作:

npm install body-parser --save

在你的 server.ts 中:

import * as bodyParser from 'body-parser';
import * as express from 'express';

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

/*
other code
*/

关于node.js - 如何在 Angular 4 Universal 中发出 http post 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44734307/

相关文章:

node.js - 使用 NodeJs 将文档插入 Mongodb 返回文档,但它不在集合中

javascript - 读取远程文件,并输出到浏览器。处理文本和 html。不要使用图像。 NodeJs

node.js - 如何使用 Koa 修复 Azure Functions 中的 "Choose either to return a promise or call ' did'"

typescript - angular2 router.navigate inside auth0 回调

angular - Angular2 中处理错误的最佳实践

angular - 如何使用 sebm google map 中的许多 map 标记动态更改缩放比例?

node.js - 带有 id 的 express 路由器

node.js - 通过 Passport 策略在路由中传递用户信息

javascript - MEANJS 获取 URL 参数

javascript - 如何在 Express.js 中迭代 POST 请求的主体?