How to configure Node.js to serve Angular 4 frontend from a specific folder?

Hey everyone,

I’m working on a project where I need to serve my Angular 4 frontend from a specific folder using Node.js. The folder structure looks like this:

project/
├── frontend/
│   └── (Angular 4 files)
└── app.js

I want to make it so that when someone visits www.xyz.com/frontend, they see my Angular app. I’m not sure how to set this up in my app.js file.

Has anyone done something similar before? What changes do I need to make in app.js to point to the right folder? Any tips or code snippets would be super helpful!

Thanks in advance for your help!

I have encountered a similar scenario in several projects. One effective approach is to use Node.js’s built-in ‘path’ module to create absolute paths for your static assets. In your app.js, for instance, you can do:

const express = require('express');
const path = require('path');
const app = express();

app.use('/frontend', express.static(path.join(__dirname, 'frontend')));

This configuration serves your Angular application from the designated ‘frontend’ folder. Additionally, to manage routing for a single-page application, you can add a catch-all route:

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'frontend/index.html'));
});

Remember to build your Angular project before serving it with Node.js.

hey there! have you tried using express.static middleware? it’s pretty neat for serving static files. somethng like:

app.use(‘/frontend’, express.static(‘path/to/frontend’));

might do the trick. curious to hear if you’ve explored other options? what challenges have you run into so far?

hey GrowingTree! i’ve done this before. u could try setting up a proxy in ur angular config. in ur proxy.conf.json, add:

{
“/api”: {
“target”: “http://localhost:3000”,
“secure”: false
}
}

then update angular-cli.json to use it. works like a charm! lmk if u need more help