I'm using Node.js and Express to build a REST api. The database operations are in a separate file called "db.js". Here's the gist of the code:
...
const db = require('./db');
app.get('/b50api/workitems/me/:pernr', function (req, rs) {
db.getWorkItems("200805").then((items, output)=>{
console.log("ITEMS:", items);
console.log("OUTPUT:", output);
}).catch(err => {
console.log("ERROR:", err);
})
})
...
When I hit this endpoint the program fails with the error below.
I created a test .js file (below) and this runs just fine:
const db = require('./db');
function test() {
db.getWorkItems("200805").then((items, output)=>{
console.log("ITEMS:", items);
console.log("OUTPUT:", output);
}).catch(err => {
console.log("ERROR:", err);
})
}
test();
What am I missing??
Here's the error information when running in my REST api:
(node:14612) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
(node:14612) UnhandledPromiseRejectionWarning: TypeError: p.callNotify is not a function
at C:\inetpub\wwwroot\PersonnelApps\b50api\node_modules\msnodesqlv8\lib\procedure.js:332:11
at C:\inetpub\wwwroot\PersonnelApps\b50api\node_modules\msnodesqlv8\lib\procedure.js:305:13
at C:\inetpub\wwwroot\PersonnelApps\b50api\node_modules\msnodesqlv8\lib\procedure.js:194:9
at runNextTicks (internal/process/task_queues.js:62:5)
at processImmediate (internal/timers.js:429:9)
(node:14612) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:14612) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Turns out the issue was it was attempting to connect to the database as some built-in account. I need to change the site to an application and change the account it's running under to the one that needs to authenticate to the SQL Server (along with making that same account one that can log on as a service).
Related
that is my raw response from API call who im trying to get each "bloc" result with a .forEach
const app = express();
const axios = require('axios')
jobList = [];
app.get('/getAPIResponse', function(req, res) {
async function myFunction() {
axios.get('https://api...')
//res.json(body)
.then((result) => {
result.results.forEach((element) => {
console.log(element)
this.jobList.push(element)
});
})
}
myfunction();
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
but the problem is, it made me some error on my terminal
(rejection id: 2)
(node:81826) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'forEach' of undefined
at /Users/mac/Desktop/alternatics_test/index.js:22:24
at processTicksAndRejections (internal/process/task_queues.js:95:5)
(node:81826) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:81826) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'forEach' of undefined
at /Users/mac/Desktop/alternatics_test/index.js:22:24
at processTicksAndRejections (internal/process/task_queues.js:95:5)
(node:81826) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 4)
to be as clear as possible results is the keyword in the api from which I would like to take each result block for insert in my "jobList"
I looked everywhere and the forEach seems to be the right technique for this...
You are using module axios
That will return a response with axios response schema
So you have to get result like this result.data.results then you can use forEach function
use result.data.results.forEach
Every time a message is sent in a specific channel, I want to print it to the console (with console.log). I am also going to color it with npm install colors. I go everywhere, even on Stack Overflow, but I cannot seem to find any information. I am coding a Scholastic Bowl-helping bot. Below is the code I have tried (I found this on Stack Overflow.)
message.fetch({ limit: 1 }).then(messages => {
let lastMessage = message.first();
if (message.channel.lastMessage = 'channel-id'){
console.log(lastMessage.red);
}
})
(Note that when I say 'channel-id' I mean the actual ID of the channel.)
The error I am getting is that message.first is not a thing.
How do I fix this error, and how can I get the most recent message in discord.js?
Edit: The exact error I got is this:
(node:12352) UnhandledPromiseRejectionWarning: TypeError: messages.first is not a function
at C:\Users\[user redacted]\Desktop\SchoBot\index.js:57:32
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:12352) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:12352) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Below is the edit for the 3rd comment on this question (sorted by oldest):
message.channel.fetch({ limit: 1 }).then(messages => {
let lastMessage = message.channel.first();
if (message.channel.lastMessage = 'channel-id'){
console.log(lastMessage.red);
}
})
Use message.channel.messages.fetch() instead of message.channel.fetch().
I didn't find the message.first function in the discord.js documentation, so I am not sure if it works. But you don't really need that function to fetch a message. The fetch function already did that for you.
In your case, the option limit: 1 will only return the most recent message, which is the command you use to trigger the fetch. If you want to fetch the most recent message but not your command, you should use limit: 2 instead and remove your command in the object later.
The fetch function will return an object containing message id and the content.
I assume that message.fetch needs to be message.channel.fetch
I'm making a discord bot and if I type $join into chat, I want the bot to join the voice channel that I'm in, and play a random sound.
case"join":
message.delete( {timeout: 5000})
const voiceChannel = message.member.voice.channel
if(voiceChannel) {
const connection = await voiceChannel.join()
const soundFile = fs.readFileSync("./sounds/")
const randFiles = soundFile[Math.floor(Math.random() * randFiles.length)]
const dispatcher = connection.play(randFiles)
} else {
message.reply("you need to be in a voice channel!").then(message => message.delete( {timeout: 5000}))
}
break;
I'm getting this error:
(node:13932) UnhandledPromiseRejectionWarning: Error: EISDIR: illegal operation on a directory, read
at Object.readSync (fs.js:524:3)
at tryReadSync (fs.js:349:20)
at Object.readFileSync (fs.js:386:19)
at Client.<anonymous> (C:\Users\PC\Desktop\doge_bot\doge-bot.js:124:38)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:13932) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13932) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not
handled will terminate the Node.js process with a non-zero exit code.
Have you read the documentation for readFileSync()? The only OS that readFileSync() successfully returns data on a directory path is on FreeBSD.
Instead, what it appears you're trying to do is grab a list of the files at a directory path; for this you could use fs.readdirSync():
const soundFile = fs.readdirSync("./sounds/")
fs.readFileSync("./sounds/") is for reading the contents of a file.
You're probably looking for fs.readdirSync("./sounds/") which gives you an array of files in a directory.
Hello in my nodejs api i need fetch data inside the loop and then again need to do a loop and save a data in another table how should i achive that?
Here is some snippet that i have tried but not succeeded for the same
async myAPIname(){
let _this = this;
try {
const bets = await Bet.find({gameId:ObjectId(request.matchId)}).lean()
bets.map(async (bet) => {
let Users = await Users.findOne({_id:ObjectId(element.userId)}).lean();
Users.parentTree.map(async (user) => {
console.log(user);
// also over here based on the some calculation need to save the data in another table
})
})
} catch (error) {
_this.res.send({ status: 0, message: error });
}
}
Also in above snipped tried with foreach loop as well but not succeeded
and error from above spinet like this:
(node:30886) UnhandledPromiseRejectionWarning: ReferenceError: Cannot access 'Users' before initialization
at /var/www/html/api/app/controllers/SomeController.js:228:30
at Array.map (<anonymous>)
at SomeController.myAPIname (/var/www/html/api/app/controllers/SomeController.js:227:18)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:30886) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:30886) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:30886) UnhandledPromiseRejectionWarning: TypeError: Assignment to constant variable.
at /var/www/html/api/app/controllers/SomeController.js:220:27
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:30886) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
Any Help will really appreciated
I can see two problems:
firstly the await inside a map call doesn't work like you think. It will work fine in a for-of loop but not in a map, foreach etc.
https://zellwk.com/blog/async-await-in-loops/ has a good an explanation as anywhere.
Secondly where you are calling let Users = Users.findOne, the compiler thinks that Users on the left hand side of the assignment is the same as the Users on the right hand side so it complains that when its calling Users.findOne, Users isn't initialised.
to use asynchronous handling with Array.prototype.map() you have to wrap it with Promise.all() and wait for it to fulfill.
!! however notice that iterations are executed in asynchronous way, not waiting for previous iteration to settle.
const sleep = async (time = 3000) => new Promise(resolve => setTimeout(resolve, time));
(async () => {
const array = [1,3,4,2];
console.log('start', array);
const mapped =await Promise.all(array.map(async e => {
await sleep(e * 1000);
console.log(e);
return `done for ${e}`;
}));
console.log('end', mapped);
})();
Hello there is my code below I have a problem since this afternoon I have two errors in the console:
UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:90699) [DEP0018]
DeprecationWarning: Unhandled promiserejections are deprecated. In the future, promise rejectionsthat are not handled will terminate the Node.js process witha non-zero exit code.
I switched to mongo client upstairs I think it's fine though the promised line 11 I think it's not fine
import {MongoClient} from 'mongodb'
MongoClient.connect('mongodb://localhost:27017/chatapp',
{userNewUrlParser:true});
export default class Database{
connect(){
return new Promise((resolve, reject) => {
MongoClient.connect(URL, (err, db) => {
return err ? reject(err) : resolve(db);
});
});
}
}
What's wrong? What's missing?