简体   繁体   English

为什么我无法从我的requirejs配置访问我的REST网址

[英]Why can't I access my REST urls from my requirejs config

I am trying to set up a REST url in my requirejs config. 我正在尝试在我的requirejs配置中设置REST URL。 Here is my config: 这是我的配置:

  require.config({
    config: {
      url: 'http://test.herokuapp.com'
    }
  });

I then try to access the url in my module: 然后,我尝试访问模块中的网址:

define(function(require, exports, module) {
  'use strict';

  var Backbone = require('backbone');
  var url = module.config().url;

  var SessionModel = Backbone.Model.extend({
    url: url + '/login'
  });
  return SessionModel;
});

I then fire up my app, and when I try to hit the url I get this error: 然后,我启动我的应用程序,当我尝试访问该网址时,出现以下错误:

POST http://99.44.242.76:3000/app/undefined/login 404 (Not Found) 

My url is undefined. 我的url未定义。 How do I access this piece of my config file in a module? 如何在模块中访问我的配置文件?

The config setting works on a per-module basis. config设置基于每个模块工作。 The config setting is an object which has for keys module names, and module.config() returns only the value associated with the name of the module that calls it. config设置是一个具有键模块名称的对象,而module.config()仅返回与调用它的模块名称相关的值。 So you'd have to put your module name in your configuration: 因此,您必须将模块名称放入配置中:

require.config({
  config: {
    my_module: {
      url: 'http://test.herokuapp.com'
    }
  }
});

Where my_module should be the actual name of your module. 其中my_module应该是模块的实际名称。 Then the url setting will be available as module.config().url (which is what you are already using). 然后, url设置将作为module.config().url (您已经在使用的module.config().url )提供。

If you want the url setting to be available to all modules, one thing you can do is to create a module that merely exports its config. 如果希望url设置可用于所有模块,则可以做的一件事就是创建一个仅导出其配置的模块。 For instance, if I call this module global : 例如,如果我将此模块称为global

require.config({
  config: {
    global: {
      url: 'http://test.herokuapp.com'
    }
  }
});

Then global.js could contain something like: 然后global.js可能包含以下内容:

define(function(require, exports, module) {
  'use strict';

  return module.config();
});

And then the module you had in your question could be something like this: 然后,您在问题中遇到的模块可能是这样的:

define(function(require, exports, module) {
  'use strict';

  var global = require("global");
  var Backbone = require('backbone');

  var url = global.url;

  var SessionModel = Backbone.Model.extend({
    url: url + '/login'
  });
  return SessionModel;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM