gpt4 book ai didi

javascript - Angular2 路由与 Express 路由结合使用?

转载 作者:IT老高 更新时间:2023-10-28 23:10:09 25 4
gpt4 key购买 nike

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

所以我有一个路由 (/docs),它提供一些静态内容和一些其他静态资源,但是,/ 被路由到一个 index.html,它被管理通过 Angular 2。因此,通过打开应用程序根目录,然后单击各种路由器链接,我可以到达一个路由,例如/tutorial/chapter/1。但是,由于这不是我的 express 应用程序中的注册路线,如果我刷新页面,我会得到 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;

您可以查看完整的 repo here

这里是路由中间件定义:

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;

最佳答案

Angular 2 假设独立于请求 URL,前端将被返回。这个假设是基于现代浏览器实现的称为 push state 的特性。如果你想支持除浏览器的前沿之外的任何东西,你有 3 个选项:

  • 推荐:将 API 服务器与客户端分开。
    如果你把你的客户端放在 example.org 上,而你的 express 后端放在 api.example.org 上,你就可以做 Angular 认为正确的事情。您也可以独立部署,客户端可以位于静态主机或 CDN 上。不过,这将要求您设置 CORS。

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

    app.use(function(req, res, next) {
    res.sendFile("index.html");
    })
  • 对路由器使用旧的浏览器 URL 样式。
    您可以让 NG2 路由器对路由使用哈希。查看 here .

关于javascript - Angular2 路由与 Express 路由结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39006659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com