Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add express into angular-starter?

I have been developing my angular2 app with webpack and angular using webpack-dev-server from here: https://github.com/AngularClass/angular-starter

I want to use express to run the application, what is the simplest way I can get there? I have npm installed express already.

like image 438
Rolando Avatar asked Jan 03 '23 20:01

Rolando


2 Answers

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.

like image 154
Dhyey Avatar answered Jan 13 '23 10:01

Dhyey


Express on top on node.js is a tool that allows you to build quickly back end rest servers.

Angular is the Front End framework.

From an application developed with Angular you can call http rest services which are exposed using Express. Apart from this there is no other relationship between Angular and Express, as there is no relationship between Angular and any server which exposes http services.

like image 31
Picci Avatar answered Jan 13 '23 08:01

Picci