javascript - Angular Express 刷新后从错误的 URL 获取文件

标签 javascript angularjs node.js express

我正在开发这个小型 MEAN 堆栈应用程序,当单击我的图像时,它会显示带有图像信息的部分内容,一切正常,但刷新后 Angular 尝试从错误的网址获取 app.js 文件:例如:http://localhost:3000/image/56afc07d5e1fea4839791b55它将 get 请求发送到 http://localhost:3000/image这是错误的,因此它找不到 Angular app.js 文件。

我如何在 Node 中提供静态文件:

app.use(express.static(path.join(__dirname, '/public')));
app.use('/bower_components',  express.static(__dirname + '/bower_components'));
app.use('/node_modules',  express.static(__dirname + '/node_modules'));
app.use('/uploads', express.static(__dirname + "/uploads"));

app.get('/*', function(req, res) {
  res.sendFile(__dirname +'/public/index.html');
});

这是 Angular app.js 中的路由:

app.config(function(
    $routeProvider, 
    $locationProvider) {

    $routeProvider
    .when('/', {
        templateUrl: '/partials/main.html',
        access: {restricted: false}
    })
    .when('/signup', {
        templateUrl: '/partials/signup.html',
        controller: 'authCtrl',
        access: {restricted: false}
    })
    .when('/login', {
        templateUrl: '/partials/login.html',
        controller: 'authCtrl',
        access: {restricted: false}
    })
    .when('/gallery', {
        templateUrl: '/partials/gallery.html',
        controller: 'authCtrl',
        access: {restricted: true}
    })
    .when('/image/:id', {
        templateUrl: '/partials/imageView.html',
        controller: 'imageViewCtrl',
        access: {restricted: true}  
    })
    .otherwise({
        redirectTo: '/'
    });

更新

仅当使用参数刷新页面时才会出现问题,例如:localhost:3000/image/id。在 localhost:3000/image 上刷新时没有问题,在 localhost:3000/image/id 上刷新并重新加载页面时,它会尝试从 localhost:3000/image 而不是 localhost:3000 获取数据

最佳答案

我的错误非常愚蠢。 Express 正确路由应用程序,但是在我添加的 index.html 文件中

Angular 的 app.js 文件:

<script type="text/javascript" src="app.js"></script>

app.js 之前没有 "/" 因此,如果 url 比 localhost:3000/gallery 更长,例如:

localhost:3000/gallery/image Angular 尝试相应地下载 app.js localhost:3000/gallery。

将app.js脚本添加到index.html的正确方法

<script type="text/javascript" src="/app.js"></script>

关于javascript - Angular Express 刷新后从错误的 URL 获取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35258266/

相关文章:

javascript - 为什么不能在内置的 Electron 应用程序中读取package.json?

javascript - Angularjs watch 未触发

javascript - removeClass 不是 AngularJS 指令中的函数

node.js - 如何使用 Passport 验证 React 应用程序?

node.js - 为什么 proto buffer 没有日期数据类型?

javascript - 将参数传递给 Node js API 调用?

javascript - Keyup 和 blur 同时触发

javascript - 在 Firebase 中搜索查询

javascript - 在 Backbone.js 中有条件地执行路由

javascript - Protractor AngularJS 计数、复制和验证列表跨度