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

让angular-cli工程基于ExpressJS服务,为对接后台API做准备

发布时间:2020-12-17 09:25:52 所属栏目:安全 来源:网络整理
导读:在angular-cli生成的工程文件目录下,创建server子目录,在server目录下创建app.js和api.routes.js,app.js内容: //参考资料: https://scotch.io/tutorials/mean-app-with-angular-2-and-the-angular-cli#conclusionconst express = require('express');co

在angular-cli生成的工程文件目录下,创建server子目录,在server目录下创建app.js和api.routes.js,app.js内容:

//参考资料: https://scotch.io/tutorials/mean-app-with-angular-2-and-the-angular-cli#conclusion

const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');

// Get our API routes
const api = require('./api.routes');

const app = express();

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Point static path to dist
app.use(express.static(path.join(__dirname,'../dist')));

// Set our api routes
app.use('/api',api);

// Catch all other routes and return the index file
app.get('*',(req,res) => {
  res.sendFile(path.join(__dirname,'../dist/index.html'));
});

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port',port);

/**
 * Create HTTP server.
 */
const server = http.createServer(app);

/**
 * Listen on provided port,on all network interfaces.
 */
server.listen(port,() => console.log(`API running on localhost:${port}`));

api.routes.js内容:

const express = require('express');
const router = express.Router();

/* GET api listing. */
router.get('/',res) => {
  res.send('api works');
});

module.exports = router;

修改package.json中scripts内容,其中start和build内容修改成

"start": "node server/app.js","build": "ng build --watch",

安装express

$ npm install --save express body-parser

运行

$npm start & npm run build 注:& 符号并行运行两侧命令,如果是&&,是顺序执行两侧命令

浏览器中访问 http://localhost:3000

(编辑:李大同)

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

    推荐文章
      热点阅读