Can’t connect Express.js server to the Angular frontend

Can't connect Express.js server to the Angular frontend

Connecting an Express.js server to an Angular frontend can sometimes be tricky. There could be multiple reasons why the server and frontend are not connecting, but here are a few common ones:

CORS issue

The most common issue is a CORS (Cross-Origin Resource Sharing) error. This occurs when the server and frontend are running on different domains or ports. The browser will block any requests made from a different origin unless the server explicitly allows it.

To fix this, you need to enable CORS on the server. You can do this by adding the CORS middleware to your Express.js app:


const express = require('express');
const cors = require('cors');

const app = express();

app.use(cors());

// your routes here

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Incorrect API endpoint

Another common issue is an incorrect API endpoint. If the frontend is calling an API endpoint that doesn't exist on the server or has a typo, it won't be able to connect.

Make sure that your API endpoint exists on the server and that the URL matches on both the frontend and backend.

Firewall issue

If you're running the server and frontend on different networks, it's possible that a firewall is blocking the connection. Make sure that the necessary ports are open and that your firewall rules allow traffic between the two networks.

Code example


// server.js

const express = require('express');
const cors = require('cors');

const app = express();

app.use(cors());

app.get('/api/data', (req, res) => {
  const data = {
    message: 'Hello from the server!'
  };

  res.send(data);
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

// data.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private readonly apiUrl = 'http://localhost:3000/api/data';

  constructor(private http: HttpClient) {}

  getData() {
    return this.http.get(this.apiUrl);
  }
}

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe