在angularjs中使用不同的域进行开发和生产

时间:2016-06-16 13:27:33

标签: angularjs gulp

我正在开发使用REST服务的AngularJS单页面应用程序。前端应用程序是与后端分开开发的,因此在开发过程中我们要在AJAX调用的URL中对域名进行硬编码(我们已经启用了CORS)。但是在生产的情况下,一切都在同一个域中运行,因此对域名进行硬编码看起来并不坏。我们是否可以在开发期间使用url中的域名进行ajax调用,而且在生产中不对域名进行硬编码?我正在使用gulp。

2 个答案:

答案 0 :(得分:1)

gulp-ng-constant$http interceptor

一起使用的示例

gulpfile.js中的以下任务将生成包含内容target/build/scripts/_config.js的文件angular.module('globals', []).constant('apiContextPath', '...');

gulp.task('app.ngconstant', [], function() {
    var ngConstant = require('gulp-ng-constant'),
    var rename = require('gulp-rename');

    return
        ngConstant({
            constants: {
                apiContextPath: '.' // TODO Devise a way to set per environment; eg command line
            },
            name: 'globals',
            stream: true
        })
        .pipe(rename('_config.js'))
        .pipe(gulp.dest('target/build/scripts'));
});

显然,您需要在生成的(打包/缩小的)代码中包含生成的文件。

以下代码中的某些内容会将$httpProvider配置为将apiContextPath添加到以'/api/'开头的所有请求(即我们的REST端点):

angular.module(...).config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push(['globals', function(globals) {
        return {
            'request': function(config) {
                if( config.url.indexOf('/api/') === 0 ) {
                    config.url = globals.apiContextPath + config.url;
                }
                return config;
            }
        };
    }]);
}]);

(还有很多其他配置选项,所以这只是我工作的旧项目的一个例子。)

答案 1 :(得分:0)

如果你还没有,你可以通过你的gulp构建一个参数来构建生产或开发模式。

基于该标志,您可以在gulpfile中设置一个baseUrl属性,该属性用于在所有角度脚本之前将脚本(使用gulp-insert)包含到您的javascript构建中:

'window.baseUrl = ' + baseUrl

然后,您的应用程序中可能会有一个常量,您的服务将使用该常量来获取baseUrl

angular.module('YourModule').constant('baseUrl', window.baseUrl);
相关问题