javascript - $locationProvider html5mode 导致刷新时出现 "cannot GET"错误 - AngularJS Node 应用程序

标签 javascript angularjs node.js mongodb .htaccess

我正在尝试使用 locationProvider 从我的 Angularjs 应用程序的 URL 中删除主题标签,并且在我手动刷新页面之前它效果很好。这总是会导致浏览器中出现“cannot GET ..”错误。我做了一些研究,我认为我必须使用 .htaccess 文件来重定向,但我不确定如何实现它,并且我已经在网上搜索了解决方案,但到目前为止还没有运气。

这是我的 app.js,它处理到我的 Angular View 和 Controller 的路由:

(function () {
    'use strict';
    var myApp = angular.module('myApp', ['ngRoute']);
    myApp.config(function($routeProvider, $locationProvider) {
        $routeProvider.
            when('/', { 
                templateUrl: 'views/partials/play.html',
                controller: 'playCtrl'
            }).
            when('/dictionary', {
                templateUrl: 'views/partials/dictionary.html', 
                controller: 'dictionaryCtrl'
            }).
            when('/add', {
                templateUrl: 'views/partials/word.html', 
                controller: 'wordCtrl'
            }).
            when('/about', {
                templateUrl: 'views/partials/about.html', 
                controller: 'aboutCtrl'
            }).

            otherwise({redirectTo: '/'});

        // use the HTML5 History API
        $locationProvider.html5Mode(true);
    });
})();

我还在 <head> 中添加了这个在我的index.html中:

<base href="/">

如果有帮助的话,该应用程序是使用 Node.js、Express、Angular 和 Mongodb 构建的。

非常感谢。

最佳答案

如果其他人想知道您需要将 Node 未使用的所有路由重定向到 Angular:

app.get('*', function(req, res) {
  res.sendfile('./path/to/index.html')
})

这必须在 server.js 中完成。不要忘记在 sendfile 链接中使用 ./:)

关于javascript - $locationProvider html5mode 导致刷新时出现 "cannot GET"错误 - AngularJS Node 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36634280/

相关文章:

node.js - 构建脚本在 Windows 上失败,但在 Linux 或 OSX 上不会

javascript - 同时运行 gulp 和 express

node.js - node-forge 如何从文件中读取私有(private) rsa key

javascript - HTML 文件选择和 JavaScript

javascript - 在 Angular 中,你总是需要继承 Controller 中的服务变量吗?

javascript - Angular ui-router,通过 url/url 变量保存状态?

javascript - ui-router,如何解析本地结果,然后解析远程结果

javascript - 是否有条件地呈现 React 组件而不是原始标记以节省性能?

php - Javascript 连接到 websocket

javascript - $ ("#id").val() 与 document.getElementById ("id").value 的工作方式不同