【问题标题】:"Cannot GET" nested state with AngularJS ui-router, html5Mode, and ExpressAngularJS ui-router、html5Mode 和 Express 的“无法获取”嵌套状态
【发布时间】:2018-02-26 20:20:13
【问题描述】:

目前我正在尝试让$locationProvider.html5Mode(true) 与 AngularJS、ui-router 和 ExpressJS 一起工作。给定带有 URL /parent 的抽象状态 parent 和带有 URL /child 的嵌套状态 parent.child,导航到网页本身内的 localhost:3000/parent/child 就可以了。但是,当在同一个 URL 上刷新页面(或直接在地址栏中输入 URL)时,浏览器会返回一条消息“Cannot GET /parent/child”。

我们一直在尝试一些不同的配置,例如 ExpressJS 和中间件。这些设置不能解决我们的问题:

app.use(express.static(__dirname + "/public"));

app.get("/", function(req, res, next) {
    console.log(req.url);
    res.sendFile(__dirname + "/public/index.html");
});

返回“无法获取”错误。

app.use(express.static(__dirname + "/public"));

app.get("*", function(req, res, next) {
    console.log(req.url);
    res.sendFile(__dirname + "/public/index.html");
});

由于 Express 使用 <script> 标记为 index.html 中的 js 文件请求发送 index.html,因此每个 js 文件都会向 (Chrome) 开发者控制台发送错误 Uncaught SyntaxError: Unexpected token <

导航到localhost:3000/parent 之类的网址时,网页显示正常,没有任何错误。

更新:我应该提一下,.js 文件的请求 URL 变成了 /parent/js/someJsFile.js,例如,在刷新 localhost:3000/parent/child 时。

【问题讨论】:

    标签: javascript angularjs node.js express angular-ui-router


    【解决方案1】:

    通常的做法是将您的静态资源保存在可以隔离并由静态中间件提供服务的位置(正因如此)。

    推荐 将您的静态资产(即 js 文件)移动到为静态资源指定的位置。

    然后,上面的第二个配置是修复:

    app.use(express.static(__dirname + "/public/static")); //<-- JavaScript here
    
    app.get("*", function(req, res, next) {
        console.log(req.url);
        res.sendFile(__dirname + "/public/index.html");
    });
    

    或者 您可以使用 urlrewrite 中间件来实现您的目标:https://github.com/kapouer/express-urlrewrite

    【讨论】:

    • 嗯...这两种解决方案仍然没有运气。 :( 我用更多信息更新了我原来的问题。
    • 啊...您的index.html 文件中是否设置了&lt;base&gt; 标签?
    • 是的:&lt;base href="/"&gt;
    • 该死 - 你正在扼杀我所有的好主意! :-)。说真的,现在失去了更多的洞察力。这是一个非常基本的设置,听起来一切都非常好。接下来要尝试的是将path.resolve()res.sendFile(...) 一起使用
    • 对不起,更具体地说,res.sendFile(path.resolve(__dirname) + ...)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 2014-12-21
    相关资源
    最近更新 更多