node.js + express error: cannot read property 'url' of undefined - node.js

I'm fairly new to Node.js, installing it to try out the DrupalChat (v7dev) module. I believe this problem is with either node.js or express, as I am beyond the stage where the chat module's settings are loaded. I am faced with the following output when trying to start the chat server
Extension loaded: drupalchat_nodejs.server.extension.js
Started http server.
info - socket.io started
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Cannot read property 'url' of undefined
at Function.handle (/usr/local/lib/node_modules/npm/node_modules/express/node_modules/connect/lib/proto.js:105:18)
at Server.app (/usr/local/lib/node_modules/npm/node_modules/express/node_modules/connect/lib/connect.js:60:31)
at Server.serverListening (/usr/local/lib/node_modules/npm/node_modules/socket.io/node_modules/policyfile/lib/server.js:136:16)
at Server.g (events.js:154:14)
at Server.emit (events.js:64:17)
at Array.1 (net.js:710:10)
at EventEmitter._tickCallback (node.js:192:40)
I remember when express installed, it gave a warning like ".... bugs['web'] should probably be bugs['url']" (I can't remember the prefix)
So is it that the server is trying to read an (API?) variable 'url' but its currently 'web'?
I have all the modules up to date, is it that I should downgrade? Or is there some way of working around this using another module?
EDIT:
line 201 is the last very line (delete authenticatedClients[authData.authToken];)... I just added to whole function for proper context
var authenticateClientCallback = function (error, response, body) {
if (error) {
console.log("Error with authenticate client request:", error);
return;
}
if (response.statusCode == 404) {
if (settings.debug) {
console.log('Backend authentication url not found, full response info:', response);
}
else {
console.log('Backend authentication url not found.');
}
return;
}
var authData = false;
try {
authData = JSON.parse(body);
}
catch (exception) {
console.log('Failed to parse authentication message:', exception);
if (settings.debug) {
console.log('Failed message string: ' + body);
}
return;
}
if (!checkServiceKey(authData.serviceKey)) {
console.log('Invalid service key "', authData.serviceKey, '"');
return;
}
if (authData.nodejsValidAuthToken) {
if (settings.debug) {
console.log('Valid login for uid "', authData.uid, '"');
}
setupClientConnection(authData.clientId, authData, authData.contentTokens);
authenticatedClients[authData.authToken] = authData;
}
else {
console.log('Invalid login for uid "', authData.uid, '"');
delete authenticatedClients[authData.authToken];
}
}

Per #thesnufkin's post, looks like the underlying express version currently pulled is not stable. Roll back to 2.5.9 and you should be good to go:
npm uninstall express
npm install express#2.5.9

As requested,
The v7 chat module from drupal is not stable. You should not use it in production.
Check bugs : http://drupal.org/project/issues/drupalchat?status=All&categories=All
Check forums : http://drupalchat7.botskool.co.in/?q=forum
Still looking for a new maintener:
"New maintainer wanted - please ping beejeebus if you're interested!".

nodejs module has this issue, so I don't think its related to the drupalchat server specifically. Here is the issue for that: http://drupal.org/node/1537702

The option to use node.js as backend in DrupalChat is currently under development. It also depends when (date on which) you downloaded the DrupalChat since the dev code is updated everyday, if new code is committed.
Please raise an issue for the same at this link - http://drupal.org/project/issues/drupalchat?status=All&categories=All.
Thanks,
darklrd

Related

ReferenceError: Cannot access 'web3' before initialization

chrome-browser-output
chrome-console
After installing the create-react-app package and then creating the web3.js file and adding the console.log(web3.version) to the App.js file im getting the above error and im not sure how to fix it and to get it working.
Ive also tried the following and it still throws the same error.
window.addEventListener('load', async () => {
// Modern dapp browsers...
if (window.ethereum) {
window.web3 = new Web3(ethereum);
try {
// Request account access if needed
await ethereum.enable();
// Acccounts now exposed
web3.eth.sendTransaction({/* ... */});
} catch (error) {
// User denied account access...
}
}
// Legacy dapp browsers...
else if (window.web3) {
window.web3 = new Web3(web3.currentProvider);
// Acccounts always exposed
web3.eth.sendTransaction({/* ... */});
}
// Non-dapp browsers...
else {
console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
}
});
Error can happen if you haven't called window.ethereum.enable(); yet.

Slack node js program running session shut down

Sorry to disturb. I am programming a Slack robot to reply user message by using the API
In the morning, it works totally okay. Then after I returned back from my office it just shut down and show me this error
Jiatongs-MacBook-Pro:news-bot jiatongli$ node index.js
Assertion failed: token must be defined
/Users/jiatongli/Desktop/news-bot/node_modules/vow/lib/vow.js:105
throw e;
^
Error: not_authed
at _api.then.fail (/Users/jiatongli/Desktop/news-bot/node_modules/slackbots/index.js:46:33)
at Array.<anonymous> (/Users/jiatongli/Desktop/news-bot/node_modules/vow/lib/vow.js:773:56)
at callFns (/Users/jiatongli/Desktop/news-bot/node_modules/vow/lib/vow.js:24:35)
at process._tickCallback (internal/process/next_tick.js:61:11)
Emitted 'error' event at:
at _api.then.fail (/Users/jiatongli/Desktop/news-bot/node_modules/slackbots/index.js:46:19)
at Array.<anonymous> (/Users/jiatongli/Desktop/news-bot/node_modules/vow/lib/vow.js:773:56)
at callFns (/Users/jiatongli/Desktop/news-bot/node_modules/vow/lib/vow.js:24:35)
at process._tickCallback (internal/process/next_tick.js:61:11)
Jiatongs-MacBook-Pro:news-bot jiatongli$
I personally have no idea what is going on because it seems like the program itself do not have bug. What i miss?
Here is the code in my index.js file:
var SlackBot = require("slackbots");
var request = require("request");
var NewsAPI = require("newsapi");
var unirest = require("unirest");
var API_KEY = process.env.API_KEY;
var Slack_API = process.env.Slack_API;
// create a bot
var bot = new SlackBot({
token: Slack_API,
name: "aloha-ai"
});
bot.on("message", msg => {
switch (msg.type) {
case "message":
// we only want to listen to direct messages that come from the user
if (msg.channel[0] === "D" && msg.bot_id === undefined) {
getRandomTechNews(postMessage, msg.user)
}
break
}
})
const postMessage = (message, user) => {
bot.postMessage(user, message, {
as_user: true
});
}
const getRandomTechNews = (callback, user) => {
unirest.get("https://nuzzel-news-v1.p.rapidapi.com/news?count=10&q=product")
.header("X-RapidAPI-Host", "nuzzel-news-v1.p.rapidapi.com")
.header("X-RapidAPI-Key", API_KEY)
.end(function (response) {
var newsJSON = response.body;
var news = "*Viral News* in product : \n\n\n\n";
for (i = 0; i < newsJSON.results.stories.length; i++) {
news += "_Excerpt:_ \n" + ">" + newsJSON.results.stories[i].excerpt + "\n"
news += "_Let's see the article!_ \n" + newsJSON.results.stories[i].url + "\n\n\n"
};
callback(news, user);
});
}
Your error message seems to indicate that your program is not authenticated with the Slack API: Error: not_authed
Since you are retrieving your API key and token from environment variables:
var API_KEY = process.env.API_KEY;
var Slack_API = process.env.Slack_API;
my guess is that you have started a new terminal session where you have not yet set that environment variable, or you are on a different computer where it is not set.
Before running your program, try exporting those variables from the command line:
export API_KEY=<my-api-key>
export Slack_API=<my-token>
If you have security concerns about your API keys showing up in your bash history you can do one of two things (these are examples of things that I do, but there are probably better, safer practices out there):
You can put an empty space before your command [space]export API_KEY=<my-api-key> instead of export API_KEY=<my-api-key>. This will make it so the command does not show up in your history.
You can put your export commands in a separate file called e.g., ~/.secrets and then run the command source ~/.secrets which will run your export commands.
Probably these will give you a sense of security rather than actual security though, since you can just echo the value of the environment variables, but I personally like taking one of these steps as an extra precaution.
i use this answer and can solve it.
Add a bot https://my.slack.com/services/new/bot and put the token
do you get token for your bot from above url:
did you set this ?

putBotAlias not working in AWS LexModelBuildingService node.js

I've been trying to replace the existing LexBot Alias(named LATEST) with a newly created bot version.
Now, according to aws documentation
When you want to update a bot alias, set the checksum field to the checksum of the most recent revision of the $LATEST version.
I can see the Alias LATEST is using bot version 12 in the Lex Console.
I have tried getting the checksum using the following (I am using getBot(...) of LexModelBuildingService to get checksum of the bot):
using Alias name itself as version i.e. LATEST.
setting versionOrAlias in getBot method params as '$LATEST'.
Hardcoding the version to 12in getBot(..).
I have used checksum from the above scenarios, but the error seems to be same as
PreconditionFailedException: The checksum value doesn't match for the resource named 'LATEST'.
Here's code snippet
async putBotAlias(botVersionResponse){
let checksum;
await this.getBot(botVersionResponse.name,'12').then(botRes=>{ // have used 12, LATEST, $LATEST with same error
console.log("Checksum For Latest: " + botRes.checksum);
checksum = botRes.checksum;
});
var params = {
botName: botVersionResponse.name,
botVersion: (parseInt(botVersionResponse.version,10)).toString(),
name: 'LATEST',
checksum : checksum
};
// checksum: checksum
console.log("Params in putBotAlias : " + JSON.stringify(params));
return new Promise((resolve,reject)=>{
this.modelBuildingService.putBotAlias(params, function(err, data) {
if (err){
reject(err);
} // an error occurred
else{
console.log("Put Alias Response :::" + JSON.stringify(data));
resolve(data);
} // successful response
});
});
}
I am really at lost here as to what version exactly it wants.
Any help is greatly appreciated.
PS: Please mention any additional required information in comments.
Apparantly I was putting checksum of 'Bot' and not of the 'BotAlias' which I was trying to put.
Updated code gets the checksum of bot Alias :
async putBotAlias(botVersionResponse,aliasName){
let checksum;
if(typeof aliasName != "undefined"){
await this.getBotAlias(botVersionResponse.name,aliasName).then(res=>{
console.log("Checksum For Latest ALIAS : " + res.checksum);
checksum = res.checksum;
}).catch((err)=>{
console.log(" Unable to getBotAlias checksum " + err);
});
}
Silly mistake, but hope it helps anyone making it. :)

How to render a page to pdf after a redirection?

QUESTION
I am trying to get a pdf of a report from a website which needs login. So I am first logging in to the website which then redirects to the page I want access to. I need to hook the onLoadFinished function to the page.render function. Here is the code I am using:
page.open(BASE_URL + Report_URL).then(function(status) {
console.log(status);
try{
page.evaluate(function(){
setTimeout(function(){
document.getElementById("username").value = "admin";
document.getElementById("password").value = "admin";
document.getElementById("submit").click();
},100)
})
page.property('onLoadFinished', function(status,page) {
console.log('==== onLoadFinished()');
try{
console.log(' status: ' + status );
page.render("report.pdf")
}catch(ex){
var fullMessage = "\nJAVASCRIPT EXCEPTION";
console.log(fullMessage);
}
},page);
}catch(ex){
var fullMessage = "\nJAVASCRIPT EXCEPTION";
console.log(fullMessage);
}
});
BUT,
Nothing happens, even exception does not come.
How can this be achieved? I want to chain the onloadFinished function to another function which can render the page as pdf...pls help!!
Environment
OS: Ubuntu 14
Node version (node -v): v6.2.2
package version: npm - 3.9.5
I solved it by using this.render instead of page.render.
Details here:- https://github.com/amir20/phantomjs-node/issues/675#issuecomment-312733078

'process.nextTick(function() { throw err; })' - Undefined is not a function (mongodb/mongoose)

I'm trying to connect to my mongodb using nodejs and socket.io. I am able to connect to the database because I get 'connection accepted' in my console but on the nodejs side, as soon as I - indeed - get
Connection to mongodb://localhost:27017 established through mongoose
it immediately fails next with
process.nextTick(function() { throw err; }) ^TypeError: undefined is
not a function at showCollections**
And here goes showCollections:
var showCollections = function(db, callback) {
mongoose.connection.db.collectionNames(function(error, names) {
if (error) {
throw new Error(error);
} else {
console.log("=>Listening mongo collections:");
names.map(function(cname) {
mongoose.connection.db.dropCollection(cname.name);
console.log("--ยป"+cname.name);
});
}
});
}
And here is the content of my database folder:
_tmp (empty folder)
local.0
local.ns
mongod.lock
I run the mongodb by typing mongod --dbpath folder and it successfully 'awaits connections on port 27017'.
Also, my node_modules from package.json (npm)
"dependencies": {
"express": "^4.9.6",
"socket.io": "latest",
"mongodb": "~2.0",
"mongoose": "*"
}
Thank you very much for your help...
StackTrace:
> TypeError: undefined is not a function
> at showCollections (/usr/share/nginx/www/index.js:77:25)
> at NativeConnection.callback (/usr/share/nginx/www/index.js:46:3)
> at NativeConnection.g (events.js:199:16)
> at NativeConnection.emit (events.js:104:17)
> at open (/usr/share/nginx/www/node_modules/mongoose/lib/connection.js:485:10)
> at NativeConnection.Connection.onOpen (/usr/share/nginx/www/node_modules/mongoose/lib/connection.js:494:5)
> at /usr/share/nginx/www/node_modules/mongoose/lib/connection.js:453:10
> at /usr/share/nginx/www/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js:59:5
> at /usr/share/nginx/www/node_modules/mongoose/node_modules/mongodb/lib/db.js:200:5
> at connectHandler (/usr/share/nginx/www/node_modules/mongoose/node_modules/mongodb/lib/server.js:272:7)
EDIT:
I'm as well having these problems when trying to run the nodejs instance:
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
I tried fixing them as other questions here would tell but nothing worked either...
From the provided information, it looks like you are using mongodb 2.0 driver. The db.collectionNames method was dropped. Check out the "Db Object" section of this page - https://github.com/mongodb/node-mongodb-native/blob/0642f18fd85037522acf2e7560148a8bc5429a8a/docs/content/tutorials/changes-from-1.0.md#L38
They've replaced it with listCollections. You should get the same effect with:
mongoose.connection.db.listCollections().toArray(function(err, names) {
if (err) {
console.log(err);
}
else {
names.forEach(function(e,i,a) {
mongoose.connection.db.dropCollection(e.name);
console.log("--->>", e.name);
});
}
});
For me this error started popping up when i had to force shut down my pc as it became unresponsive. Next time i started my express server this error popped up. I solved it by running npm install mongoose#4.0 --save in the terminal.
May be this error pops up when your server or database is force closed and some code is not save in mongod behind the scenes.
Shouldn't you specify the full path and have an export module?...something like:
mongoose.connection.db.collectionNames(function (err, names)
{
console.log(names); // [{ name: 'dbname.myCollection' }]
module.exports.Collection = names;
}
If I'm wrong it's because I don't fancy moongodb :)

Resources