I am creating a contactform with Angular 18 and Express js for the backend. I created and API to send the email when the form is completed. Don’t know why but i don’t receive email anymore when i complete the form from my frontend. But when i try with postman, everything is ok. I don’t have any issue in my console even if i put many try catch in my code. Don’t know if it is the cors because i allowed them in my code.
Here is my server.js
const express = require(‘express’);
const nodemailer = require(‘nodemailer’);
const bodyParser = require(‘body-parser’);
const cors = require(‘cors’);
require(‘dotenv’).config();const app = express();
app.use(bodyParser.json());
app.use(cors({
origin: ‘http://localhost:4200/’,
methods: ‘GET,HEAD,PUT,PATCH,POST,DELETE’,
allowedHeaders: ‘Content-Type,Authorization’
}));app.post(‘/api/contact’, async (req, res) => {
const { name, email, message } = req.body;try {
const transporter = nodemailer.createTransport({
service: ‘gmail’,
auth: {
user: process.env.EMAIL_USER,
pass: process.env.APP_SPECIFIC_PASSWORD,
},
tls: {
rejectUnauthorized: false,
},
});const mailOptions = {
from: email,
to: process.env.EMAIL_USER,
subject:New message from ${name}
,
text: message,
};await transporter.sendMail(mailOptions);
res.status(200).json({ message: ‘Email sent successfully!’ });
catch (error) {
console.error(‘Error sending email:’, error);
res.status(500).json({ error: ‘Failed to send email’ });
}
});const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(Server is running on port ${PORT}
);
});
here is my component.service.ts
import { Component, OnInit } from ‘@angular/core’;
import { FormBuilder, FormGroup, Validators } from ‘@angular/forms’;
import { ContactService } from ‘./contact-service.service’;
import { firstValueFrom } from ‘rxjs’;
import { HttpClient, HttpHeaders } from ‘@angular/common/http’;@Component({
selector: ‘app-contacts’,
templateUrl: ‘./contacts.component.html’,
styleUrl: ‘./contacts.component.css’
})
export class ContactsComponent implements OnInit {contactForm: FormGroup;
confirmationMessage: boolean = false;
formSubmitted: boolean = false;constructor(
private contactService: ContactService,
private http: HttpClient,
private fb: FormBuilder) {
this.contactForm = this.fb.group({
name: [”, Validators.required],
email: [”, [Validators.required, Validators.email]],
message: [”, Validators.required]
});
}ngOnInit(): void {
if (localStorage.getItem(‘formSubmitted’) === ‘true’) {
this.confirmationMessage = true;
localStorage.removeItem(‘formSubmitted’);
window.scrollTo(0, document.getElementById(‘contacts’)!.offsetTop);
}
}onSubmit(): void {
if (this.contactForm.valid) {
this.contactService.sendMessage(this.contactForm.value)
.then(() => {
localStorage.setItem(‘formSubmitted’, ‘true’);
window.location.reload();
})
.catch((error) => {
console.error(‘Error sending message:’, error);
});
}
}
}
Here is my service.ts
import { HttpClient, HttpHeaders } from ‘@angular/common/http’;
import { Injectable } from ‘@angular/core’;
import { firstValueFrom} from ‘rxjs’;@Injectable({
providedIn: ‘root’
})
export class ContactService {private apiUrl = ‘http://localhost:3000/api/contact’;
constructor(private http: HttpClient) {}
sendMessage(contactData: { name: string; email: string; message: string }): Promise {
const headers = new HttpHeaders({
‘Content-Type’: ‘application/json’
});return firstValueFrom(this.http.post(this.apiUrl, contactData, { headers, withCredentials: true }));
}
}
Here is my proxy
{
“/api”: {
“target”: “http://localhost:3000”,
“secure”: false,
“changeOrigin”: true,
“logLevel”: “debug”
}
}
Can somebody help me please?
I tried even without a proxy but same thing