0
votes

I am trying to load the npm request module, inside of a requirejs define function.

define(function () {
console.log("run");
var request = require('request');
request('http://www.google.com', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body) // Show the HTML for the Google homepage.
    }
})
});

When the browser hits the require('request') , it throws this error.

Uncaught Error: Module name "request" has not been loaded yet for context: _. > Use require([])

From my understanding both nodejs and requirejs define a require() function, so In the tutorial example, https://github.com/request/request I believe when they call require() it is using the nodejs require function, but in my case it thinks require is something different. If this is in fact the problem, how can I change the require() function name for either require or node?

1

1 Answers

1
votes

If I install RequireJS and request and create a file named test.js that contains:

var requirejs = require("requirejs");

requirejs("foo");

And in the same directory I create a file named foo.js that contains your code:

define(function () {
console.log("run");
var request = require('request');
request('http://www.google.com', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body) // Show the HTML for the Google homepage.
    }
})
});

And I execute:

$ node test.js

Then I get run on the console plus the body of the page.

I've tried variants:

  • Import RequireJS as require: var require = require('requirejs')

  • Use the async form of the call: requirejs(["foo"])

  • Various mixtures of the above.

I cannot reproduce the behavior you report.