This question already has answers here:
Can I use jQuery with Node.js?
(21 answers)
Closed 4 years ago.
I have tried npm install jQuery --save and in my node file var $ = require('jquery'); but, then when I run my node file with
$.getJSON('https://en.wikipedia.org/wiki/Washington,_D.C.', function(data) {
//data is the JSON string
});
I get the error
TypeError: $.getJSON is not a function
at Object.<anonymous> (C:\Users\Karim\node 2\tweetPic.js:16:3)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
I have also tried importing jquery using
require("jsdom").env("", function(err, window) {
if (err) {
console.error(err);
return;
}
var $ = require("jquery")(window);
});
which just returns
TypeError: require(...).env is not a function
at Object.<anonymous> (C:\Users\Karim\node 2\tweetPic.js:3:18)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
I have installed the jsdom package in a similar fashion. Is there something wrong with my jquery code itself? How can I fix this?
Edit: It seems jQuery isn't really what I need here. I'm just going to look into a different way of retrieving json data.
Sorry but i don't know how to install jquery. But you apparently need it to request a website and fetch json. You could use request for that. Hope i helped you.
And you could do like :
request('https://en.wikipedia.org/wiki/Washington,_D.C.', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});
Related
I created a Node.js rest api. It follows the general controller, model, schema structure and uses a restify server which I start by running node index.js.
The controller consists of a controllers/baseController.js which contains some operations relevant to all of my controller classes. My controllers/issues.js which extends controllers/baseController.js initially only had a GET, POST and PUT operations. Whilst not complete, these worked fine. They certainly didnt prevent the server fron starting.
I then added the following delete action to my controller:
controller.addAction({
'path': '/issues',
'method': 'DELETE',
'summary': 'Delete all issues from the list',
'responseClass': 'Issues',
'nickname': 'deleteIssues'
}, controller.delete);
It routes to:
delete(req, res, next) {
let collectionContents = this.lib.db.model('Issues');
collectionContents.remove({}, (err, result) => {
if(err) return next(this.RESTError('InternalServerError', err));
this.writeHAL(res, result);
});
}
However, when I try to start my server I get this error:
Debugger listening on ws://127.0.0.1:30333/71b18332-4ac6-49b8-b0ac-86517e9a2190
Debugger attached.
/Users/paulcarron/git/issue-tracker/controllers/baseController.js:19
app[method.toLowerCase()](act['spec']['path'], act['action']);
^
at Issues.setUpActions (/Users/paulcarron/git/issue-tracker/controllers/baseController.js:15:18)
at Object.setupRoutes (/Users/paulcarron/git/issue-tracker/lib/helpers.js:13:12)
at Object.<anonymous> (/Users/paulcarron/git/issue-tracker/index.js:35:13)
at Module._compile (module.js:632:14)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Function.Module.runMain (module.js:676:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
TypeError: app[method.toLowerCase(...)] is not a function
baseController.js:19
at actions.forEach.act (/Users/paulcarron/git/issue-tracker/controllers/baseController.js:19:32)
at Array.forEach (<anonymous>)
at Issues.setUpActions (/Users/paulcarron/git/issue-tracker/controllers/baseController.js:15:18)
at Object.setupRoutes (/Users/paulcarron/git/issue-tracker/lib/helpers.js:13:12)
at Object.<anonymous> (/Users/paulcarron/git/issue-tracker/index.js:35:13)
at Module._compile (module.js:632:14)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Function.Module.runMain (module.js:676:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
Waiting for the debugger to disconnect...
baseController.js is here.
It seems to have an issue with 'method': 'DELETE'. However, I can't figure out why. I thought it may be Swagger related as I believe the functions such as addGET, addPOST etc are there and that maybe addDELETE doesn't exist but I checked and it's there. Can anybody explain what might be wrong here?
Additional info.
I think I'm making some progress. The specific point where I'm getting my issue is with method.toLowerCase(). When setting up DELETE, this is essentially DELETE.toLowerCase() but this isn't allowed because delete is a reserved word(I think). Does that seem correct and if so how wo I resolve it?
So I'm trying to solve an issue that PG-Promise is giving me, but I'm not entirely certain as to why. I'm very certain that I set up the database and environment for it correctly, and have properly seeded and tested the database locally. If needed be, I can link the respective queries I have that make calls to the database, but I'm not sure if that'll help solve this.
That said, below is the pg-promise environment and the exact error it's firing. I appreciate any help with solving this!
const promise = require('bluebird');
promise object has .catch/,then etc..
const options = {
promiseLib: promise
};
const pgp = require('pg-promise')(options);
const connectionString = process.env.DATABASE_URL;
my .env's database url is the following: DATABASE_URL=postgres://localhost:5432/project3//
const db = pgp(connectionString);
db.connect()
.then(obj => {
obj.done();
})
.catch(error => {
console.log('ERROR:', error.message || error);
});
TypeError: Invalid connection details.
at inst (/Users/benjidurden/Documents/projects/mighty-shelf-36224/node_modules/pg-promise/lib/main.js:177:15)
at Object.<anonymous> (/Users/benjidurden/Documents/projects/mighty-shelf-36224/routes/queries2.js:12:12)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/Users/benjidurden/Documents/projects/mighty-shelf-36224/routes/index.js:4:10)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
If you just look at the code, then it is obvious that your process.env.DATABASE_URL is either null or an empty string, neither of which is a valid connection string, hence the error.
my .env's database url is the following: DATABASE_URL=postgres://localhost:5432/project3
You presume so, but I'm betting that it is not.
UPDATE
Following this question, I have refactored the initialization errors in pg-promise, to include the details of what is in fact being passed in, available from v5.7.2.
I'm trying to write a little test of realm-js using node.js console, but after insertion of te first string I see an exception:
> var Realm = require('realm')
TypeError: utf8 is not a function
at Function.from (native)
at Function.from (native)
at module.exports (/home/hermann/node_modules/realm/lib/submit-analytics.js:92:60)
at Object.<anonymous> (/home/hermann/node_modules/realm/lib/index.js:70:42)
at Module._compile (module.js:410:26)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
Anybody can help me with this problem?
UPD. An error occures in realm/lib/submit-analytics.js in this call:
request(`https://api.mixpanel.com/track/?data=${Buffer.from(JSON.stringify(payload), 'utf8').toString('base64')}&ip=1`,
() => { /* Analytics failed. Do nothing. */ });
That's a bug, you must be using Node.js 4.x? I've created an issue to track this -- for now you can just comment out that entire line to make it work for you.
This question is not the same as Extended Errors do not have message or stack trace, which deals with es6 extends, but I'm using es5.
Here's my code
test.js
function FooError(message) {
this.stack = (new Error(message)).stack;
console.log('this.stack', this.stack);
console.log('new_error_stack', (new Error(message)).stack);
console.log('after');
}
FooError.prototype = new Error;
throw new FooError("foo");
This gives the following output : with node version 6.4 (node test.js)
this.stack Error
at Object.<anonymous> (/tmp/test.js:7:22)
at Module._compile (module.js:556:32)
at Object.Module._extensions..js (module.js:565:10)
at Module.load (module.js:473:32)
at tryModuleLoad (module.js:432:12)
at Function.Module._load (module.js:424:3)
at Module.runMain (module.js:590:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
new_error_stack Error: foo
at Error.FooError (/tmp/test.js:4:33)
at Object.<anonymous> (/tmp/test.js:9:7)
at Module._compile (module.js:556:32)
at Object.Module._extensions..js (module.js:565:10)
at Module.load (module.js:473:32)
at tryModuleLoad (module.js:432:12)
at Function.Module._load (module.js:424:3)
at Module.runMain (module.js:590:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
after
/tmp/test.js:9
throw new FooError("foo");
^
Error
at Object.<anonymous> (/tmp/test.js:7:22)
at Module._compile (module.js:556:32)
at Object.Module._extensions..js (module.js:565:10)
at Module.load (module.js:473:32)
at tryModuleLoad (module.js:432:12)
at Function.Module._load (module.js:424:3)
at Module.runMain (module.js:590:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
as you can see, the 'this.stack' doesn't show the same thing at all than the 'new_error_stack', eg, the this.stack shows the stack as if the error was thrown when the require was called. Also, the thrown stack is also "incorrect".
I took the code from https://stackoverflow.com/a/5251506/1993501 , and since I want to use instanceof FooError, I use the line FooError.prototype = new Error.
As you can see, the 'new_error_stack' gives the expected output, but I would have expected both values to be equal.
This has the effect that errors are not very useful for users of my library, see corresponding issue : https://github.com/open-xml-templating/docxtemplater/issues/245
What exactly is happening, and how can I prevent it and keep proper error types (eg being able to use instanceof) ?
I found a possible solution to your problem, but I'm not entirely sure it fixes all of your issues. I'm using Error.prototype instead of new Error (which is what you had). I found this solution from the first answer provided to this question: How do I create a custom Error in JavaScript?
I also changed your console.log lines to concatenate the two strings, as I was using alert() to display the output for testing purposes.
Kevin Hakanson goes over why you may or may not want to go with this solution in his answer. Here's the code to answer your question:
function FooError(message) {
this.stack = (new Error(message)).stack;
console.log('this.stack ' + this.stack);
console.log('new_error_stack ' + (new Error(message)).stack);
console.log('after');
}
FooError.prototype = Error.prototype;
throw new FooError("foo");
You may want to use a try/catch block with that last line.
In Node.js, if I have a method that throws an exception, console.log statements from that method don't fire. I recognize that in the simple test case below that I should catch the exception from the readFileSync call, or otherwise be defensive about it. Just curious if someone could explain the behavior to me.
Simple test case:
var fs = require('fs');
function readAFileThatDoesntExist(filename) {
console.log(filename);
fs.readFileSync(filename);
}
console.log("We're about to read a file that doesn't exist!");
readAFileThatDoesntExist("afile");
Output:
$ node test.js
We're about to read a file that doesn't exist!
fs.js:338
return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
^
Error: ENOENT, no such file or directory 'C:\blog\projects\bloggen\scripts\afile'
at Object.fs.openSync (fs.js:338:18)
at Object.fs.readFileSync (fs.js:182:15)
at readAFileThatDoesntExist (C:\blog\projects\bloggen\scripts\test.js:5:8)
at Object.<anonymous> (C:\blog\projects\bloggen\scripts\test.js:9:1)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
Ah, figured it out.
It seems that console.log isn't finishing before the process exits... If I use console.warn, the message does show up.
This post explains it: is node.js' console.log asynchronous?
Also, I'm on an older version (0.8.15), so this may no longer be relevant.