Angularjs应用程序运行在本地主机上,而不是在heroku上

angularjs app running on localhost but not on heroku

本文关键字:heroku 主机 应用程序 运行 Angularjs      更新时间:2023-09-26

我的angularjs应用程序在本地主机上运行得很好。但当我将它部署到heroku时,应用程序显示出来,但一些功能,主要是前端到后端通信失败。我怀疑这是因为我使用了http://localhost:3000而不是我的真实网站地址:https://mytestapp.herokuapp.com。有人能让我知道我应该做什么让这个应用程序在heroku上运行?后端与前端通信,使登录/注册功能运行。目前,当我登录或注册时,我得到一个错误,好像什么都没有发生。

我运行grunt build,并从.gitignore中删除/dist,并有一个procfileweb: node api.js

和我的包。Json文件如下:

  "version": "1.0.0",
  "main": "Gruntfile.js",
  "directories": {
    "test": "test"
  },
  "scripts": {
    "start": "nf start",
    "test": "echo '"Error: no test specified'" && exit 1"
  },

我还在我的app.config.js中声明了一个常量,如:

  .constant('API_URL', 'http://localhost:3000/')

我使用API_URL设置我的登录/注册authproviders.

和在我的gruntfile.js中,我也有以下几位:

connect: {
  options: {
    port: 9000,
    // Change this to '0.0.0.0' to access the server from outside.
    hostname: 'localhost',
    livereload: 35729
  },
  livereload: {
    options: {
      open: true,
      middleware: function (connect) {
        return [
          connect.static('.tmp'),
          connect().use(
            '/bower_components',
            connect.static('./bower_components')
          ),
          connect().use(
            '/app/styles',
            connect.static('./app/styles')
          ),
          connect.static(appConfig.app)
        ];
      }
    }
  },
  test: {
    options: {
      port: 9001,
      middleware: function (connect) {
        return [
          connect.static('.tmp'),
          connect.static('test'),
          connect().use(
            '/bower_components',
            connect.static('./bower_components')
          ),
          connect.static(appConfig.app)
        ];
      }
    }
  },

更新

我试图在这个控制器中实现它,但没有成功:当我实现Yoni的解决方案时,我不再得到projectlist,它显示了一个空页面。为什么呢?

'use strict';
angular.module('ModuleV11App')
  .controller('ProjectlistCtrl', function ($http, $scope, API_URL, alert) {
    return $http.get($rootScope.server.url + '/projectlist').success(function (projectlist) {
      $scope.projectlist = projectlist;
    }).error(function (err) {
      alert('warning', "Unable to get projects, please login first", err.message);
    })
  });

但是,它可以工作,当它像这样:

return $http.get(API_URL + 'projectlist').success(function (projectlist) {

使用$location服务

你可以这样做:

angular.module('mainModule', [])
    .run(function($location,$rootScope) {
        $rootScope.server = {url: location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '')};
    })

然后你可以在你的前端代码的任何地方有这样的调用:

$http.get($rootScope.server.url + '/whatever');