在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