Here is a demo file for your application Express:
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) => {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
return res.json({
code: '0',
msg: 'Successfully called test API'
})
})
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 using node start server/server.jsin one terminal and npm run server:dev:hmrin another.
API call from home.component.ts:
public ngOnInit() {
console.log('hello `Home` component');
this.http.get('http://localhost:3001/test')
.map(res => res.json())
.subscribe(data => console.log("data received", data))
}
You can see on your network tab developer tools that the request was made to the server.
npm run build:prod, - dist.