I have a small javascript module that produces signed certificates that works perfectly on a standard browser but I need to port it onto a server running node.js I am using the technique suggested by Koen, here Load “Vanilla” Javascript Libraries into Node.js, and wrapping the three libraries as he suggested
var jsjws = {};
( function(jsjws) {
.....
})(jsjws);
console.log("jsjws",jsjws);
module.exports = jsjws
etc. After some effort I have managed to get the jsjws libraries to work and then figured out that I also needed (for compatibility) to port of the standard XMLHttpRequest library. On the npm site they have the download for a library XMLHttpRequest. However it does not want to import using the given require syntax, i.e.
var XMLHttpRequest = require("./node_modules/XMLHttpRequest/xmlhttprequest.js").XMLHttpRequest;;
The error message being given is:
[0] => jsjws {} 1 => module.js:327 2 => throw err; [3] => ^ [4] => [5] => Error: Cannot find module './node_modules/XMLHttpRequest/xmlhttprequest.js' [6] => at Function.Module._resolveFilename (module.js:325:15) [7] => at Function.Module._load (module.js:276:25) [8] => at Module.require (module.js:353:17) [9] => at require (internal/module.js:12:17) [10] => at Object. (C:\xampp-5.6.23\htdocs\
The code that I am using is shown below and would appreciate any insight into why it is not working. That having been said it does work using node-debug
when XMLHttpRequest.js is in the same directory as the source files.
eval(require('fs').readFileSync('./node_modules/jsjws/jws-3.2.js', 'utf8'));
eval(require('fs').readFileSync('./node_modules/jsjws/jsrsasign.js.js', 'utf8'));
var XMLHttpRequest = require("./node_modules/XMLHttpRequest/xmlhttprequest.js").XMLHttpRequest;
var pHeader = {"alg":"RS256","typ":"JWT"}
var sHeader = JSON.stringify(pHeader);
var pClaim = {};
pClaim.aud = "https://www.googleapis.com/oauth2/v3/token";
pClaim.scope = "https://www.googleapis.com/auth/fusiontables";
pClaim.iss = "cl@routesproofofconcept.iam.gserviceaccount.com";
pClaim.exp = KJUR.jws.IntDate.get("now + 1hour");
pClaim.iat = KJUR.jws.IntDate.get("now");
var sClaim = JSON.stringify(pClaim)
var key = "-----BEGIN PRIVATE KEY-----\nMF+ZY....";
var sJWS = KJUR.jws.JWS.sign(null, sHeader, sClaim, key);
var XHR = new XMLHttpRequest();
var urlEncodedData = "";
var urlEncodedDataPairs = [];
urlEncodedDataPairs.push(encodeURIComponent("grant_type") + '=' + encodeURIComponent("urn:ietf:params:oauth:grant-type:jwt-bearer"));
urlEncodedDataPairs.push(encodeURIComponent("assertion") + '=' + encodeURIComponent(sJWS));
urlEncodedData = urlEncodedDataPairs.join('&').replace(/%20/g, '+');
// We define what will happen if the data are successfully sent
XHR.addEventListener('load', function(event) {
var response = JSON.parse(XHR.responseText);
console.log(response)
token = response["access_token"]
console.log(token);
});