3

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?

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
DonutGaz
  • 1,492
  • 2
  • 17
  • 24

1 Answers1

10

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");
Andrew Li
  • 55,805
  • 14
  • 125
  • 143
  • I have posted [an answer](https://stackoverflow.com/a/46081151/2954267) about why to not use in all cases the `xmlhttprequest module`. You should check it out. – robe007 Sep 06 '17 at 17:33