【问题标题】:How to make http post request in Angular 4 Universal?如何在 Angular 4 Universal 中发出 http post 请求?
【发布时间】:2017-11-27 19:02:54
【问题描述】:

我正在开发 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 我收到所有未定义的值。 我的代码有什么问题?

谢谢。

【问题讨论】:

  • 你能提供更多server.ts文件的代码吗?尤其是app.use() 条目。
  • @MaciejSobala 你好,我已经更新了server.ts 文件,谢谢。
  • 这个答案对你有用吗?
  • @MaciejSobala 我刚到家,我现在就试试,谢谢。

标签: node.js angular express nodemailer angular-universal


【解决方案1】:

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

【讨论】:

  • 非常感谢。几天来一直在努力解决这个问题。
  • 太好了。所以现在你可以接受并投票给这个答案:)
  • 在我这样做之前你应该做的一件事,app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); 应该在 app.post("/api/send", sendMailApi); 之前在 server.ts 文件中调用,然后它对我有用。请更新答案,这个小细节可以为像我这样的新人节省很多时间。
猜你喜欢
  • 2019-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-26
  • 1970-01-01
相关资源
最近更新 更多