如何在Angular 4 Universal中提出http post请求?

我正在使用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" <foo@foo.com>', to: "bhushan.foo@foo.com", 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: "foo@foo.com", 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我收到的所有值为undefined。 我的代码有什么问题?

谢谢。

您在服务器端代码中缺lessbodyParser。 执行以下操作:

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 */