I'm encountering a CORS issue when attempting to make requests from my Angular application to my Node.js backend. The error message in the browser's console is as follows:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/subscribe. (Reason: CORS request did not succeed). Status code: (null). I have a blog i'm creating. In the footer section i have a subscribe button. When a user enters their email and click the button it should save to my db. Im new to nodejs so im not sure if it's correct any advice would be great. My code is below
- Footer.html
<div class="footer">
<div class="section1">
<h3>Subscribe to Our Newsletter</h3>
<p>Stay updated with our latest ideas on recipes.</p>
<div class="subscribe-form">
<form [formGroup]="subscribeForm" (ngSubmit)="onSubmit()">
<input type="email" formControlName="email" placeholder="Enter your email" />
<button type="submit">Subscribe</button>
</form>
</div>
<div class="footer-links">
<ul>
<li><a [routerLink]="['/about']">About Us</a></li>
<li><a [routerLink]="['/contact']">Contact Us</a></li>
</ul>
</div>
</div>
<div class="logo">
<img src="assets/logotan.png" alt="Logo">
</div>
<div class="section2">
<div class="contact-info">
<p>Email: <a href="mailto:[email protected]">[email protected]</a
</p>
</div>
<div class="copyright">
<p>© {{ currentYear }} TheFoodieLeonne. All rights reserved.</p>
</div>
<div class="social-media-icons">
<a href="https://facebook.com"><i class="fab fa-facebook"></i></a>
<a href="https://twitter.com"><i class="fab fa-twitter"></i></a>
<a href="https://instagram.com"><i class="fab fa-instagram"></i></a>
<a href="https://tiktok.com"><i class="fab fa-tiktok"></i></a>
<!-- Add more social media icons as needed -->
</div>
</div>
</div>
- Footer.ts
export class FooterComponent implements OnInit {
currentYear: number = new Date().getFullYear(); subscribeForm: FormGroup;
constructor(private fb: FormBuilder, private subscribeService: SubscribeService) {
this.subscribeForm = this.fb.group({
email: ['', [Validators.required, Validators.email]]
});
}
ngOnInit() {
}
onSubmit() {
if (this.subscribeForm.valid) {
const email = this.subscribeForm.get('email')!.value;
this.subscribeService.subscribe(email).subscribe(
(response) => {
// Handle successful subscription
console.log('Subscription successful!', response);
},
(error) => {
// Log the full error object for more details
console.error('Subscription failed!', error);
}
);
}
}
}
- subscribe.service.ts
export class SubscribeService {
private baseUrl = 'http://localhost:3000'; // Replace with your backend server URL
constructor(private http: HttpClient) { }
subscribe(email: string): Observable<any> {
const url = `${this.baseUrl}/subscribe`;
// Headers to set content type to JSON
const headers = new HttpHeaders({
'Content-Type': 'application/json',
});
// Request body
const body = { email };
return this.http.post(url, body, { headers });
}
}
- app.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 3000;
// Use CORS middleware
app.use(cors());
app.use(express.json());
// Load environment variables from .env
const dotenv = require('dotenv');
dotenv.config();
// Connect to MongoDB using the environment variable
mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Import routes
const emailRoutes = require('./email.model');
app.use('/', emailRoutes);
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
});
- email.model.js
const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
// Import the Email model
const Email = require('./email.model');
// Subscribe endpoint
router.post('/subscribe', async (req, res) => {
const { email } = req.body;
try {
// Check if the email is not already in the database
const existingEmail = await Email.findOne({ email });
if (!existingEmail) {
// If not, save it to the database
const newEmail = new Email({ email });
await newEmail.save();
console.log('Email saved to the database:', newEmail);
res.status(200).send('Subscribed successfully!');
} else {
res.status(400).send('Email is already subscribed.');
}
} catch (error) {
console.error('Error saving email to the database:', error);
res.status(500).send('Internal Server Error');
}
});
// Get subscribed emails endpoint
router.get('/emails', async (req, res) => {
try {
// Retrieve all emails from the database
const emails = await Email.find({}, 'email');
res.status(200).json(emails.map((e) => e.email));
} catch (error) {
console.error('Error retrieving emails from the database:', error);
res.status(500).send('Internal Server Error');
}
});
module.exports = router;
You have to use cors middleware that Express provides. Then you will be able to solve your issue. Check it out here: https://expressjs.com/en/resources/middleware/cors.html
Like this :