我一直在使用 webpack 和 Angular 使用 webpack-dev-server 开发我的 angular2 应用程序:https://github.com/AngularClass/angular-starter https://github.com/AngularClass/angular-starter
我想使用 Express 来运行应用程序,最简单的方法是什么?我已经安装了 npm Express。
这是一个演示文件供您使用Express
app:
服务器/服务器.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
在另一个。
从 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))
}
您可以在开发人员工具的网络选项卡中看到已向服务器发出请求。
现在你可以执行npm run build:prod
并且您的所有内容仍将由dist
目录。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)