如何将 express 添加到 angular-starter 中?

Rol*_*ndo 4 express angular

我一直在使用 webpack-dev-server 从这里使用 webpack 和 angular 开发我的 angular2 应用程序:https : //github.com/AngularClass/angular-starter

我想使用 express 来运行应用程序,我可以通过什么最简单的方法到达那里?我已经安装了 npm 快递。

Dhy*_*yey 5

这是您的Express应用程序的演示文件:

服务器/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`)
})
Run Code Online (Sandbox Code Playgroud)

通过node start server/server.js在一个终端和npm run server:dev:hmr另一个终端中使用来启动服务器。

从 home.component.ts 调用 API:

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))
}
Run Code Online (Sandbox Code Playgroud)

您可以在开发人员工具的网络选项卡中看到已向服务器发出请求。

现在您可以执行npm run build:prod,您的所有内容仍将从dist目录中提供。