Here is a demo file for your Express
app:
server/server.js:
const express = require("express");
const app = express();
const bodyparser = require("body-parser");
const json = bodyparser.json;
const http = require('http').Server(app);
const urlencoded = bodyparser.urlencoded;
const path = require("path");
app.use(json());
app.use(urlencoded({
extended: true
}));
app.use(express.static(__dirname + '/../dist'));
app.get('/test', (req, res) => {
/* when using webpack-dev-server we are using webpack's url
so we need to set headers for development i.e npm run server:dev:hmr
*/
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
return res.json({
code: '0',
msg: 'Successfully called test API'
})
})
/* Only for production i.e: - All others are to be handled by Angular's router */
app.get('/*', (req, res) => {
res.sendFile(path.join(__dirname + '/../dist/index.html'));
});
http.listen(3001, function() {
console.log(`App started on port 3001`)
})
Start the server by using node start server/server.js
in one terminal and npm run server:dev:hmr
in another.
Calling the API from home.component.ts :
public ngOnInit() {
console.log('hello `Home` component');
/**
* this.title.getData().subscribe(data => this.data = data);
*/
this.http.get('http://localhost:3001/test')
.map(res => res.json())
.subscribe(data => console.log("data received", data))
}
You can see in your network tab of developer tools that a request has been made to the server.
Now you can execute npm run build:prod
and all your content will still be served from the dist
directory.