How to add express to angular-starter?

I am developing my angular2 application using 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 easiest way I can get there? I already have npm installed.

+4
source share
3 answers

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) => {
    /* when using webpack-dev-server we are using webpack 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 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 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.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 on your network tab developer tools that the request was made to the server.

npm run build:prod, - dist.

+4

node.js - , .

Angular - Front End.

, Angular, http rest, Express. Angular Express, Angular , http-.

+2

angular 2.X.X:

AngularClass express/universal

https://github.com/angular/universal-starter

For angular 4.XX Use angular platform server

https://github.com/ng-seed/universal

+2
source

Source: https://habr.com/ru/post/1679737/


All Articles