Oma*_*mar 6 node.js express typescript mean-stack angular
这是我的节点server.js,它位于项目根目录中,有自己的 npm 配置。所有 Angular 文件都在dist/client之后ng buildclient/dist
const express = require('express');
const colors = require('colors');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');
const PORT = process.env.port||'3200';
// init "app"
const app = express();
app.use(cors({origin: `http://localhost:4200`}));
// angular entry point
app.use(express.static(path.join(__dirname, 'client/dist')));
//parse incoming data before routes
app.use(bodyParser.json())
// api routes
app.use('/api',require('./api/api'));
// error middleware
app.use(function(err, req, res, next){
console.log(`${err}`.red.bold)
res.status(422).send({error: err.message });
});
// listen
app.listen(PORT, function(){
console.log(`app running on ${PORT}...`.magenta);
});
Run Code Online (Sandbox Code Playgroud)
当我访问服务器时,http://localhost:3200/我看到我的角度应用程序。当我去的时候http://localhost:3200/api/someExpressRoute我得到了我的 api 函数。伟大的
现在我需要弄清楚如何提供角度路线。例如http://localhost:3200/about是我的角度单页应用程序的一部分。但是当我访问该网址时,服务器不知道该怎么做。
如何配置此服务器以处理http://localhost:3200/*从索引提供的角度路由?
以下是我如何通过 Nodejs 为我的 Angular 应用程序提供服务:
var express = require('express'),
path = require('path'),
fs = require('fs');
var compression = require('compression');
var app = express();
var staticRoot = __dirname + '/';
var env = process.env.NODE_ENV || 'development';
app.set('port', (process.env.PORT || 5000));
app.use(compression());
/* other middleware */
/* place any backend routes you have here */
app.use(function(req, res, next) {
//if the request is not html then move along
var accept = req.accepts('html', 'json', 'xml');
if (accept !== 'html') {
return next();
}
// if the request has a '.' assume that it's for a file, move along
var ext = path.extname(req.path);
if (ext !== '') {
return next();
}
fs.createReadStream(staticRoot + 'index.html').pipe(res);
});
app.use(express.static(staticRoot));
app.listen(app.get('port'), function() {
console.log('app running on port', app.get('port'));
});
Run Code Online (Sandbox Code Playgroud)
为应用程序提供服务时,请确保所有前端 dist 文件与此文件位于同一文件夹中(我称之为index.js)
| 归档时间: |
|
| 查看次数: |
4647 次 |
| 最近记录: |