如何在express-starter中添加express? [英] How to add express into angular-starter?

查看:86
本文介绍了如何在express-starter中添加express?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在从以下位置开始使用webpack和angular使用webpack-dev-server开发我的angular2应用程序: https ://github.com/AngularClass/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

我想使用express运行应用程序,最简单的方法是什么?我已经安装了npm Express.

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

推荐答案

以下是您的Express应用的演示文件:

Here is a demo file for your Express app:

server/server.js:

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`)
})

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

Start the server by using node start server/server.js in one terminal and npm run server:dev:hmr in another.

从home.component.ts调用API:

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.

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

Now you can execute npm run build:prod and all your content will still be served from the dist directory.

这篇关于如何在express-starter中添加express?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆