Я создал контактную форму с angular 7 и интегрировал ее с nodemailer, чтобы при отправке формы детали формы отправлялись на указанный адрес электронной почты. Представление работает нормально и отлично передает значения, но когда значения отправляются в бэкэнд узла, оно становится неопределенным, в результате чего приходит электронное письмо, а значения записываются как неопределенные. Пожалуйста, посмотрите на код ниже:
Функция контроллера узла:
app.post('http://localhost:4000/api/v1/blogs'+'/send/mail', (req, res) => {
let user = {
name: req.body.name,email: req.body.email,phone: req.body.phone,message: req.body.message}
console.log(user.name) //values in this user object is coming undefined
console.log(req.body)
//nodemailer setup
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'example@gmail.com',
pass: 'password'
}
});
var mailOptions = {
from: 'example@gmail.com',
to: 'example@gmail.com',
subject: 'A new lead has Arrived!',
html: `<p>Name: ${user.name}</p>
<p>Email: ${user.email}</p>
<p>Phone: ${user.phone}</p>
<p>Message: ${user.message}</p>`
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
});
Angular .ts файл:
export class ContactComponent implements OnInit {
contactForm: FormGroup;
public formName: string;
public formEmail: string;
public formPhone: number;
public formMessage: string;
constructor(private router: Router, private blogpostService: BlogpostService,
private formBuilder: FormBuilder, private toastr: ToastrManager) { }
ngOnInit() {
this.contactForm = this.formBuilder.group({
formName: ['', Validators.required],formEmail: ['', Validators.required],formPhone: ['', Validators.required],formMessage: ['']})}
public contact() {
const formData = new FormData();
formData.append('name', this.contactForm.get('formName').value);
formData.append('email', this.contactForm.get('formEmail').value);
formData.append('phone', this.contactForm.get('formPhone').value);
formData.append('message', this.contactForm.get('formMessage').value);
this.blogpostService.contactForm(formData).subscribe(
data => {console.log(data)
this.toastr.successToastr('Your contact information is saved Susseccfully!', 'Success!');
setTimeout(() =>{
this.router.navigate(['/']);
}, 1000)
},
error => {
console.log(error);
console.log(error.errorMessage);
this.toastr.errorToastr('This is not good!', 'Oops!');
this.router.navigate(['/']);
})}}
файл службы .ts:
public contactForm(formData): Observable<any> {
let myResponse = this._http.post(this.baseUrl + '/send/mail', formData);
// console.log(formData.get('name'))
return myResponse;
}
ОБНОВЛЕНИЕ index. js:
const express = require('express')
const http = require('http')
const appConfig = require('./config/appConfig')
const fs = require('fs')
const mongoose = require('mongoose')
const cookieParser = require('cookie-parser')
const bodyParser = require('body-parser')
const globalErrorMiddleware = require ('./app/middlewares/appErrorHandler');
const routeLoggerMiddleware = require('./app/middlewares/routeLogger');
const logger = require('./app/libs/loggerLib');
//declaring an instance or creating an application instance
const app = express()
//middlewares
app.use(bodyParser.json()) //bodyParser
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser())
app.use('/uploads', express.static('uploads'))
app.use(globalErrorMiddleware.globalErrorHandler);
app.use(routeLoggerMiddleware.logIp);
// Bootstrap models
let modelsPath = './app/models'
fs.readdirSync(modelsPath).forEach(function (file) {
if (~file.indexOf('.js')) {
console.log(file)
require(modelsPath + '/' + file)
}
})
// end Bootstrap models
// Bootstrap route
let routesPath = './app/routes'
fs.readdirSync(routesPath).forEach(function (file) {
if (~file.indexOf('.js')) {
console.log("including the following file");
console.log(routesPath + '/' + file)
let route = require(routesPath + '/' + file);
route.setRouter(app);
}
});// end bootstrap route
app.use(globalErrorMiddleware.globalNotFoundHandler);
//listening the server - creating a local server
const server = http.createServer(app)
// start listening to http server
console.log(appConfig)
server.listen(appConfig.port)
server.on('error', onError)
server.on('listening', onListening)
function onError(error) {
if (error.syscall !== 'listen') {
logger.error(error.code + ' not equal listen', 'serverOnErrorHandler', 10)
throw error
}
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
logger.error(error.code + ':elavated privileges required', 'serverOnErrorHandler', 10)
process.exit(1)
break
case 'EADDRINUSE':
logger.error(error.code + ':port is already in use.', 'serverOnErrorHandler', 10)
process.exit(1)
break
default:
logger.error(error.code + ':some unknown error occured', 'serverOnErrorHandler', 10)
throw error
}
} //end of On Error
function onListening() {
var addr = server.address()
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
('Listening on ' + bind)
logger.info('server listening on port' + addr.port, 'serverOnListeningHandler', 10)
let db = mongoose.connect(appConfig.db.uri, { useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true }) //end of onListening}
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason)
// application specific logging, throwing an error, or other logic here
})
// handling mongoose connection error
mongoose.connection.on('error', function (err) {
console.log('database connection error');
console.log(err)
}); // end mongoose connection error
// handling mongoose success event
mongoose.connection.on('open', function (err) {
if (err) {
console.log("database error");
console.log(err);
} else {
console.log("database connection open success");
}}); // end mongoose connection open handler