Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 451
DonutGaz Avatar asked Jun 19 '26 01:06

DonutGaz


1 Answers

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");
like image 152
Andrew Li Avatar answered Jun 21 '26 15:06

Andrew Li



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!