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

前端之家收集整理的这篇文章主要介绍了让angular-cli工程基于ExpressJS服务,为对接后台API做准备前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在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

原文链接:https://www.f2er.com/angularjs/147646.html

猜你在找的Angularjs相关文章