我正在开发使用REST服务的AngularJS单页应用程序。前端应用程序是独立于后端开发的,因此在开发过程中,我们必须为AJAX调用(我们启用了CORS)在URL中硬编码域名。但是在生产的情况下,所有的东西都在同一个域中运行,因此硬编码的域名看起来并不坏。在开发过程中,我们可以在urls中为ajax调用使用域名吗?在生产过程中,不要硬编码域名吗?我用的是口服液。
发布于 2016-06-16 14:54:20
gulpfile.js中的以下任务将生成包含内容angular.module('globals', []).constant('apiContextPath', '...');的文件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;
}
};
}]);
}]);(还有很多其他的配置选项,所以这只是我工作过的一个旧项目的一个例子。)
发布于 2016-06-16 13:51:15
如果您还没有这样做,您可以通过gulp参数在生产或开发模式中进行构建。
基于该标志,您可以在all文件中设置一个baseUrl属性,该属性用于在所有角脚本之前将脚本(使用gulp-insert)包含到javascript构建中:
'window.baseUrl = ' + baseUrl然后,您可以在您的应用程序中有一个常量,您的服务可以使用它来获取baseUrl。
angular.module('YourModule').constant('baseUrl', window.baseUrl);https://stackoverflow.com/questions/37860704
复制相似问题