- This project sets up a Node server application using TypeScript directly within the same folder as an Angular CLI application.
*** Note: to open web links in a new window use: ctrl+click on link**
- The server is live within the Angular app directory and is written in Typescript, in root-level folder
/server
. - A JSON package was created, then the dependencies (
ts-node ts-node-dev tslint typescript express @types/express
) were added. - A
tsconfig.json
file was created so the server could have its own typescript configuration for the express server. http://localhost:4200/users
displays a users list observable using the Angular async pipe
- Angular v16
- RxJS Library v7 used to handle datastreams and propagation of change using observables.
- Concurrently v8 npm dependency used to run multiple commands concurrently.
npm i
&&cd server && npm i
to install dependencies for front & backends- To run front & backend concurrently: from root level type
npm run serve
then navigate tohttp://localhost:4200/
&http://localhost:4201/users
. The app will automatically reload if you change any of the source files.
- server.js file that generates a server from within the app.
import express from 'express';
import { routes } from './routes';
const app = express();
const port = 4201;
// allow any method from any host and console.log requests.
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, DELETE');
if ('OPTIONS' === req.method) {
res.sendStatus(200);
} else {
console.log(`${req.ip} ${req.method} ${req.url}`);
next();
}
});
// Handle POST requests that come in formatted as JSON
app.use(express.json());
app.use('/', routes);
app.listen(port, '127.0.0.1', () => {
console.log('Server now listening on port', port);
});
- App runs server from inside angular app, as a 'monorepository'. The advantages of this according to danluu.com include:
"With a monorepo, projects can be organized and grouped together in whatever way you find to be most logically consistent, and not just because your version control system forces you to organize things in a particular way. Using a single repo also reduces overhead from managing dependencies."
- Status: Working. Post does not add data to users array, possible CORS issue.
- To-Do: refresh users cards when new user added.
- Youtube Video: Adding a Node + Typescript Backend to Your Angular App.
- Stephen Fluin: Demos with Angular blog post
- Medium Article by Stephen Fluin: Adding a Node + Typescript Backend to Your Angular App
- This project is licensed under the terms of the MIT license.
- Repo created by ABateman, email:
[email protected]