DonutGaz
DonutGaz

Reputation: 1542

XMLHttpRequest not defined when using JSONLoader in Node

I'm writing a game in Three.js, and as a multiplayer game, I need to verify client positions serverside to prevent cheating. I'm currently trying to load a model on the server, as such:

var THREE = require("three");
var loader = new THREE.JSONLoader();
loader.load( './models/tree.json', function ( geometry, materials ) {
    var mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ) );
    res.send(mesh);
});

However, the server dies and spits out

var request = new XMLHttpRequest();
ReferenceError: XMLHttpRequest is not defined
    at FileLoader.load

This request is coming at node_modules\three\build\three.js:29258, where an XMLHttpRequest is made.

Why is this happening? Am I doing something wrong, or is this portion of Three.js broken for Node?

Upvotes: 3

Views: 14359

Answers (1)

Andrew Li
Andrew Li

Reputation: 57964

Three.js uses an XMLHttpRequest to load files such as your JSON file. XMLHttpRequest is built-in in browsers environments, but it's not built-in in a Node environment, so it's not defined, thus the error. You'll have to install the xmlhttprequest package through NPM to use it with Node.

Since Three.js does not require the xmlhttprequest module, you're going to have to set a global variable so that new XMLHttpRequest will work:

global.XMLHttpRequest = require("xmlhttprequest");

Upvotes: 10

Related Questions