CodexBloom - Programming Q&A Platform

Angular 13: Handling CORS errors with AJAX requests to a local API in development

👀 Views: 80 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-09
angular cors httpclient typescript

I'm confused about I'm currently developing an Angular 13 application that makes AJAX requests to a local API running on `http://localhost:3000`. When I try to send a POST request from my Angular component using the `HttpClient`, I'm facing a CORS (Cross-Origin Resource Sharing) error in the browser console. The error message states: `Access to XMLHttpRequest at 'http://localhost:3000/api/resource' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.` I've tried adding CORS middleware on the server-side using Express, like this: ```javascript const express = require('express'); const cors = require('cors'); const app = express(); app.use(cors()); // Enable CORS for all routes app.post('/api/resource', (req, res) => { res.json({ message: 'Resource created' }); }); app.listen(3000, () => { console.log('Server listening on port 3000'); }); ``` I confirmed that the server is running and the route is accessible. In my Angular service, I have a method that looks like this: ```typescript import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class ApiService { private apiUrl = 'http://localhost:3000/api/resource'; constructor(private http: HttpClient) { } createResource(data: any): Observable<any> { return this.http.post(this.apiUrl, data); } } ``` When I call `createResource()` method from my component, it throws the mentioned CORS error. I've also tried explicitly setting the `Access-Control-Allow-Origin` header on my Express server like this: ```javascript app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', 'http://localhost:4200'); res.header('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization'); next(); }); ``` However, I still get the same error. I've ensured that the server and client are not running on the same port and that I'm using the latest versions of Angular and Express. What am I missing? Is there something else I need to configure or check to resolve this CORS issue? For context: I'm using Typescript on macOS. For context: I'm using Typescript on Ubuntu. Am I missing something obvious? I've been using Typescript for about a year now.