加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何将快速添加到角度启动器?

发布时间:2020-12-17 17:51:54 所属栏目:安全 来源:网络整理
导读:我一直在使用webpack-dev-server从这里开发我的angular2应用程序和webpack: https://github.com/AngularClass/angular-starter 我想用express来运行应用程序,我能到达那里最简单的方法是什么?我已经安装了npm快递. 解决方法 这是Express应用程序的演示文件
我一直在使用webpack-dev-server从这里开发我的angular2应用程序和webpack: https://github.com/AngularClass/angular-starter

我想用express来运行应用程序,我能到达那里最简单的方法是什么?我已经安装了npm快递.

解决方法

这是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('/*',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目录中提供.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读