如何从角度2发送到快递服务器

时间:2017-08-22 01:09:02

标签: node.js angular express

新手在这里试图掌握从Angular 2向Node / Express服务器发送联系表单数据......现在我在localhost:4200上使用内置服务器托管Angular 2,并且在localhost:3000表达服务器。我尝试了以下代码,但收到以下错误:

Error: ENOENT: no such file or directory, stat 'C:\Users\corey\Desktop\Project\server\api\contact-form-submit'

这是我的contact-form.component.ts文件:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';


@Component({
  selector: 'app-contact-form',
  templateUrl: './contact-form.component.html',
  styleUrls: ['./contact-form.component.css']
})
export class ContactFormComponent {

    constructor(private http: HttpClient) {}

    onSubmit(form) {
        this.http.post('http://localhost:3000/server/api/contact-form-submit', JSON.stringify(form.value)).subscribe();
        console.log(form.value);
    }


}

这是我的server.js文件:

var express = require('express');
var nodemailer = require('nodemailer');
var mg = require('nodemailer-mailgun-transport');
var bodyParser = require('body-parser');
var app = express();
var path = require('path');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

//trying to get contact form submission from angular 2 form here
app.get('/', function (req, res) {
    res.sendfile('./api/contact-form-submit');
    console.log('test');
});

//api key and domain for mailgun
var auth = {
  auth: {
    api_key: 'api-key-here',
    domain: 'mailgun@domain here'
  }
}

//trying to send email with nodemailer here
app.post('./api/send', function(req, res) {
    var transporter = nodemailer.createTransport(mg(auth));

    var mailOptions = {
        from: 'postmaster@email.com',
        to: 'email@goeshere.com',
        subject: 'Website submission',
        text: 'Name: ' + req.body.name + 'Email: ' + req.body.email + 'Message: ' + req.body.message,
        html: '<p>Submission: </p><br><ul><li>Name: ' + req.body.name + '</li><li>Email: ' + req.body.email + '</li><li>Message: ' + req.body.message + '</li></ul>' 
    };

    transporter.sendMail(mailOptions, function(error, info) {
        if (error) {
            console.log(error);
            res.redirect('/');
        } else {
            console.log('Message sent.');
            res.redirect('/');
        }
    })

});

app.listen(3000, function() {
    console.log('Express started on port 3000');
});

我获得了在Angular 2中使用的成功表单数据,我让快速服务器发送带有常规快递帖子/获取html文件的电子邮件......但我不理解如何集成的关键部分Angular with Express并使用它向Nodemailer发送电子邮件。这里有什么帮助?谢谢。 This is my project structure.

1 个答案:

答案 0 :(得分:0)

我正在回答类似的问题How to make post request from angular to node server

从角度发布时,您需要在服务器上配置cross-origin

结帐此github回购https://github.com/kuncevic/angular-httpclient-examples