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?
Related
I'm trying to run this piece of code:
router.put('/restaurants/:id', async (req, res) => {
try {
const response = await Restaurant.findByIdAndUpdate(req.params.id, {name: req.body.name,
item_1.name: req.body.item,
item_2.name: req.body.item_2,
item_3.name: req.body.item_3,
item_4.name: req.body.item_4
})
res.send(response)
}
catch (error) {
res.send(error)
}
})
where the scenario is I have items (i.e item_1 etc) saved as objects in database, items got two properties name and rating, when admin wants to edit an item it should only be able to just edit the name property of an item not the rating, so for implementing this what i'm trying to do is, upon edit request as shown here, I want to set only the name property of an item as same to what has been sent in the request.
but it gives me a typescript error (though I don't have typescript installed) saying:
',' expected.ts(1005)
and it happens before running this code, actually vs code is showing this error.
and upon running it is showing something like this:
E:\xord\second_assignment\node\routes\restaurants.js:50
item_1.name: req.body.item,
^
SyntaxError: Unexpected token '.'
at wrapSafe (internal/modules/cjs/loader.js:1054:16)
at Module._compile (internal/modules/cjs/loader.js:1102:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Module.require (internal/modules/cjs/loader.js:1026:19)
at require (internal/modules/cjs/helpers.js:72:18)
at Object.<anonymous> (E:\xord\second_assignment\node\index.js:8:21)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
[nodemon] app crashed - waiting for file changes before starting...
same thing happens with a different error when i try to access the object property with bracket notation.
I apologise for the very long query but I'm wondering; is the syntax I've used in this code for setting the value of an object's key inside another object, incorrect? if so then why? also what would be the alternative way to do this?
thanks God! in mongoose v5.10.19 documentation I saw almost the same instance where they use a property of an object as a key of another object here:
Parent.update({}, { 'child.name': 'Luke Skywalker' }, (error) => {
// Error because parentSchema has `strict: throw`, even though
// `childSchema` has `strict: false`
});
by which I learnt that in such cases one should wrap the key in quotes as they did in "child.name". and that resolved the issue i was facing.
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.
});
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.
I have an error Not running only when I start my app.js on my server, it works on localhost.
My code is there : Github
Error: Not running
at Server.close (net.js:1233:11)
at Object.<anonymous> (/home/Nahis_Wayard/summoner-infos/app.js:13:10)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
Edit: I remove the 'server.close()' and now it works everywhere
Thanks for your help !
In your app.js, this code var server = http.createServer(app); is used.
However, the http.createServer() is async function, it returns a new instance of http.Server, and http.server inherits from net.Server and has the additional events.
So call server.close() could cause the error Error: Not running in your case.
Here is one sample codes shown the close() is invoked.
var server = http.createServer( (req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('okay');
});
server.listen(1337, '127.0.0.1', () => {
// other operations here
server.close();
});