Angular2路由与Express路由一起使用?

Geo*_*rds 12 javascript node.js express typescript angular

当通过URL访问时,我的angular2应用程序的路由不起作用... Express正在呈现错误页面.

所以我有一个route(/docs)提供一些静态内容和一些其他静态资源,然而,/路由到index.html由angular 2管理.所以通过打开应用程序根然后单击各种路由器链接,我可以到达一条路线,例如/tutorial/chapter/1.但是,由于这不是我的快递应用程序中的注册路线,如果我刷新页面,我会得到404.

我希望能够输入http://localhost:3000/tutorial/chapter/1我的浏览器并获取该页面.如何设置express来将所有未定义的路由路由到angular,并让angular处理404?

这是我的app.js:

var app = express();

// html view engine setup
app.set('views', path.join(__dirname, '/ng2/views'));
app.engine('html', require('jade').renderFile);
app.set('view engine', 'html');

app.use(express.static('ng2/views'));
app.use(express.static('ng2/public'));

app.use('/node_modules', express.static(__dirname + '/node_modules'));    

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'ng2/public', 'favicon.png')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

//all static assetes for hexo content

app.use('/docs', serveStatic('features/docs/public', { 'index': ['index.html', 'index.htm'] }));

app.use('/', routes);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});


module.exports = app;
Run Code Online (Sandbox Code Playgroud)

你可以在这里看到完整的回购

这是路由中间件def:

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

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});


module.exports = router;
Run Code Online (Sandbox Code Playgroud)

Aur*_*lia 12

Angular 2假设独立于请求URL,将返回前端.此假设基于现代浏览器实现的功能push state.如果你想支持除浏览器前沿之外的任何东西,你有3个选择:

  • 建议:从客户端分离API服务器.
    如果你打开你的客户端example.org,你的快速后端就api.example.org可以做到Angular认为是真的.您也可以独立部署,客户端可以在静态主机或CDN上运行.这将要求您设置CORS.

  • Catch-All Express Route
    确保Express中的所有路线与您在NG2中设置的路线不同,并制作一个包罗万象的处理程序.在路由/中间件的末尾,但在404处理程序之前放置这样的东西!

    app.use(function(req, res, next) {
      res.sendFile("index.html");
    })
    
    Run Code Online (Sandbox Code Playgroud)
  • 使用旧版browser-url-styles作为路由器.
    您可以使NG2路由器使用路由的哈希值.请点击这里.


Joh*_*Siu 5

app.js

由于订单很重要并且新代码插入多个位置,因此包含整个文件.寻找评论开始// JS -

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var serveStatic = require('serve-static')
var file = require('./features/prepareTutorial');
var routes = require('./ng2/routes/index');

var app = express();

// html view engine setup
app.set('views', path.join(__dirname, '/ng2/views'));
app.engine('html', require('jade').renderFile);
app.set('view engine', 'html');

app.use(express.static('ng2/views'));
app.use(express.static('ng2/public'));

app.use('/node_modules', express.static(__dirname + '/node_modules'));
app.use('/persist', express.static(__dirname + '/persist'));

// JS - Add /app
app.use('/app', express.static(__dirname + '/ng2/views/app'));

// I have to comment this line because it failed
//file.processTutorial(); //generate html rendered patches for tutorial steps
//file.genGit(); //generate git SHA
file.processChapters();

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'ng2/public', 'favicon.png')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

//all static assetes for hexo content

app.use('/docs', serveStatic('features/docs/public', { 'index': ['index.html', 'index.htm'] }));
//app.use(subdomain('docs', express.static('docs/public')));
app.use('/script', serveStatic('features/docs/public/script'));
app.use('/style', serveStatic('features/docs/public/style'));
app.use('/images', serveStatic('features/docs/public/images'));
app.use('/diff', serveStatic('features/tutorial/diffs'));
app.use('/git', serveStatic('features/git'));
app.use('/chapter', serveStatic('ng2/views/app/tutorial/chapter/chapters'));
app.use('/img', serveStatic('features/docs/source/img'));

app.use('/config', serveStatic('ng2/config'));

app.use('/', routes);

// JS - /tutorial static
//app.use('/tutorial', express.static('ng2/views/app/tutorial'));
// JS - /tutorial/chapter/* send index file 
app.all(/^\/tutorial$/, (req, res) => {
  res.redirect('/tutorial/');
});
app.use('/tutorial/', (req, res) => {
  res.sendFile(__dirname + '/ng2/views/index.html');
});

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;
Run Code Online (Sandbox Code Playgroud)

ng2/config/systemjs.config.js&ng2/public/config/systemjs.config.js

使用绝对路径

这是主要问题.使用相对路径,浏览器请求的文件tutorial/chapter/2/app/*,tutorial/chapter/2/node_modules/*等,以及应用程序彻底分解.

// snip ...
var map = {
    'app':                        '/app', // 'dist',
    '@angular':                   '/node_modules/@angular',
    'angular2-in-memory-web-api': '/node_modules/angular2-in-memory-web-api',
    'rxjs':                       '/node_modules/rxjs'
  };
// snip ...
Run Code Online (Sandbox Code Playgroud)

NG2 /视图/ index.html中

使用绝对路径

这不会阻止页面加载,但一团糟.

// snip ...
<link rel="stylesheet" href="/stylesheets/style.css">
// snip ...
Run Code Online (Sandbox Code Playgroud)