如何在Angular 4 Universal中发布http发布请求?

时间:2017-06-24 08:03:17

标签: 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" <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 中,我收到的所有值都是未定义的。 我的代码怎么了?

谢谢。

1 个答案:

答案 0 :(得分:2)

您在服务器端代码中缺少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
*/