Chat application like Slack tutorial - node.js

I am following this tutorial here: https://www.youtube.com/watch?v=a-JKj7m2LIo
I got stuck around the 14 minute mark getting the following error message in the terminal:
(node:6248) UnhandledPromiseRejectionWarning: RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: undefined
[0] at ServerResponse.writeHead (_http_server.js:237:11)
[0] at ServerResponse._implicitHeader (_http_server.js:228:8)
[0] at write_ (_http_outgoing.js:616:9)
[0] at ServerResponse.end (_http_outgoing.js:733:5)
[0] at ServerResponse.send (D:\htdocs\mern\react-slack-clone\node_modules\express\lib\response.js:221:10)
[0] at ServerResponse.sendStatus (D:\htdocs\mern\react-slack-clone\node_modules\express\lib\response.js:359:15)
[0] at D:\htdocs\mern\react-slack-clone\server.js:31:13
[0] at processTicksAndRejections (internal/process/task_queues.js:93:5)
[0] (node:6248) 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: 1)
[0] (node:6248) [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
Still learning how to use React and Node, but I think the error is occurring in my server.js file.
My server.js code looks like this:
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const Chatkit = require('pusher-chatkit-server')
const app = express()
const chatkit = new Chatkit.default({
instanceLocator: 'fhdsakfjsdalkfjdsalfjsdlajflsad',
key:
'ruewioqruewfhdsakljfdsaljfsdlakjds483294'
})
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(cors())
app.post('/users', (req, res) => {
const { username } = req.body
chatkit
.createUser({
name: username,
id: username
})
.then(() => res.sendStatus(201))
.catch(error => {
console.log('Error:', error) // updated
/*if(error.error_type === 'services/chatkit/user_already_exists') {
res.sendStatus(200)
} else {
res.sendStatus(error.statusCode).json(error)
}*/
})
})
const PORT = 3001
app.listen(PORT, err => {
if (err) {
console.error(err)
} else {
console.log(`Running on port ${PORT}`)
}
})
Basically, when I submit a name, in the console's network tab, I should see the post, but I am not. The error message is all I get but I'm not sure how to decipher it.
Edit
Added console.log('Error:', error) to the code above and received the following error message in the terminal:
Error: ErrorResponse {
[0] status: 404,
[0] headers: {
[0] 'access-control-expose-headers': 'X-Envoy-Upstream-Service-Time,
Server, Access-Control-Expose-Headers, Access-Control-Max-Age, Date',
[0] 'access-control-max-age': '86400',
[0] 'content-type': 'application/json',
[0] date: 'Tue, 17 Mar 2020 18:07:17 GMT',
[0] server: 'istio-envoy',
[0] 'x-envoy-upstream-service-time': '10',
[0] 'content-length': '209',
[0] connection: 'close'
[0] },
[0] error: 'not_found',
[0] error_description: 'Not found',
[0] error_uri: 'https://docs.pusher.com/errors/not_found'
[0] }
I do not understand what this error message means. I check the URL provided by error_uri, and the message on that page read, "The server couldn't find the requested resource. Please make sure that the name of the resource you are requesting is correct." I am not entirely sure what that means.
Edit 2
I made the following change to app.post in an attempt to produce another terminal error, as follows:
app.post('/users', (req, res) => {
const { username } = req.body
chatkit
.createUser({
name: username,
id: username
})
.then(() => res.sendStatus(201))
.catch(error => {
//console.log('Error:', error)
if(error.error_type === 'services/chatkit/user_already_exists') {
res.sendStatus(200)
} else {
//res.sendStatus(error.statusCode).json(error)
res.sendStatus(500)
console.log(JSON.stringify(error))
}
})
})
I received the following response in the terminal:
{"status":404,"headers":{"access-control-expose-headers":"Date,
X-Envoy-Upstream-Service-Time, Server, Access-Control-Expose-Headers,
Access-Control-Max-Age","access-control-max-age":"86400",
"content-type":"application/json","date":"Thu, 09 Apr 2020 02:34:22
GMT","server":"istio-envoy",
"x-envoy-upstream-service-time":"11",
"content-length":"209","connection":"close"},
"error":"not_found","error_description":
"Not found","error_uri":"https://docs.pusher.com/errors/not_found"}
I do not know what any of this means.

Related

Expected 'port' to be a 'number', got 'object', minecraft server status check error

i have this simple code in my discord bot to check mc server.
const Discord = require('discord.js')
const client = new Discord.Client()
const { MessageButton, MessageButtonStyles } = require('discord-buttons')
require('discord-buttons')(client)
const db = require('quick.db')
let mineutil = require('minecraft-server-util')
client.on('ready', () => {
console.log('Started!\n---')
client.user.setPresence({
status: 'online',
activity: {
type: 'LISTENING',
name: '!help'
}
})
})
client.on('message', async (message) => {
if (message.content == 'привет') {
message.reply('привет')
}
//more code
const SERVER_ADDRESS = 'adress'
const SERVER_PORT = 25565
const STATUS_ONLINE = '**Сервер включен** - '
const STATUS_PLAYERS = '**{online}** **человек(a) онлайн!**'
const STATUS_EMPTY = '**никто не играет**'
const cacheTime = 15 * 1000; // 15 sec cache time
let data, lastUpdated = 0;
function statusCommand(message) {
getStatus().then(data => {
let status = STATUS_ONLINE;
status += data.onlinePlayers ?
STATUS_PLAYERS.replace('{online}', data.onlinePlayers) : STATUS_EMPTY;
let statuspanel = new Discord.MessageEmbed()
.setColor('2ecc71')
.setDescription(status)
send(statuspanel)
}).catch(err => {
console.error(err)
let statuserror = new Discord.MessageEmbed()
.setColor('ff0000')
.setDescription('**Сервер выключен**')
send(statuserror)
})
}
function getStatus() {
if (Date.now() < lastUpdated + cacheTime) return Promise.resolve(data);
return mineutil.status(SERVER_ADDRESS, { port: SERVER_PORT })
.then(res => {
data = res;
lastUpdated = Date.now();
return data;
})
}
if (message.content == '!server') {
statusCommand(message)
}
})
client.login(TOKEN)
And it works in Visual studio, but i just placed it on Replit and it catches this error:
(node:172) UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: Expected 'port' to be a 'number', got 'object'
at Object.status (/home/runner/Makak-discord-bot/node_modules/minecraft-server-util/dist/status.js:23:26)
at getStatus (/home/runner/Makak-discord-bot/index.js:210:21)
at statusCommand (/home/runner/Makak-discord-bot/index.js:192:5)
at Client.<anonymous> (/home/runner/Makak-discord-bot/index.js:219:5)
at Client.emit (events.js:314:20)
at Client.EventEmitter.emit (domain.js:483:12)
at MessageCreateAction.handle (/home/runner/Makak-discord-bot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/home/runner/Makak-discord-bot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/Makak-discord-bot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/home/runner/Makak-discord-bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
(node:172) 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:172) [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.
And if i change, for example { port: SERVER_PORT } to 25565, it always says that server is off, even if server online(
PS sorry for my english, and russian text in code
EDIT Just saw the question's last line about the server being reported as offline when using a number rather than an object. That actually confirms my suspicion below, as you're no longer getting an error from the SDK itself (ie, it seems to be "working," in that it's at least making the network call). I would double-check your address and port number, and ensure the server is accessible from replit.
--- Original response below ---
Difficult to say for sure without knowing the mineutil API you're using, but it looks like you may be sending more than you need to the mineutil.status() function (And if you're using this library, I'm fairly certain you are).
I'm guessing that the following line:
return mineutil.status(SERVER_ADDRESS, { port: SERVER_PORT })
which is sending an object `{port: SERVER_PORT}' as its second parameter, should just be sending the number itself. For example:
return mineutil.status(SERVER_ADDRESS, SERVER_PORT )
This is Replit server side error, it can not be repaired(

Having problems when making a ticket discord JS

haveing problem when makeing a ticket i dunno what i did everything looks right it would be nice for some help on. i dunno what i did wrong. it looks to me like something went wrong with "message.guild.channels.create" when it trys to create it, it gives me this error the code and the error is below
module.exports = {
name: "ticket",
aliases: [],
permissions: [],
description: "open a ticket!",
async execute(message, args, cmd, client, discord) {
const channel = await message.guild.channels.create(`ticket: ${message.author.tag}`);
channel.setParent("855596395783127081");
channel.updateOverwrite(message.guild.id, {
SEND_MESSAGE: false,
VIEW_CHANNEL: false,
});
channel.updateOverwrite(message.author, {
SEND_MESSAGE: true,
VIEW_CHANNEL: true,
});
const reactionMessage = await channel.send("Thank you for contacting support!");
try {
await reactionMessage.react("🔒");
await reactionMessage.react("⛔");
} catch (err) {
channel.send("Error sending emojis!");
throw err;
}
const collector = reactionMessage.createReactionCollector(
(reaction, user) => message.guild.members.cache.find((member) => member.id === user.id).hasPermission("ADMINISTRATOR"), { dispose: true }
);
collector.on("collect", (reaction, user) => {
switch (reaction.emoji.name) {
case "🔒":
channel.updateOverwrite(message.author, { SEND_MESSAGES: false });
break;
case "⛔":
channel.send("Deleting this channel in 5 seconds!");
setTimeout(() => channel.delete(), 5000);
break;
}
});
message.channel
.send(`We will be right with you! ${channel}`)
.then((msg) => {
setTimeout(() => msg.delete(), 7000);
setTimeout(() => message.delete(), 3000);
})
.catch((err) => {
throw err;
});
},
};
Heres the error
PS C:\Users\lolzy\OneDrive\Desktop\discordbot> node .
Cbs slave is online!
(node:19344) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'channels' of undefined
at Object.execute (C:\Users\lolzy\OneDrive\Desktop\discordbot\commands\ticket.js:7:45)
at module.exports (C:\Users\lolzy\OneDrive\Desktop\discordbot\events\guild\message.js:10:26)
at Client.emit (events.js:376:20)
at MessageCreateAction.handle (C:\Users\lolzy\OneDrive\Desktop\discordbot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\lolzy\OneDrive\Desktop\discordbot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\lolzy\OneDrive\Desktop\discordbot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\Users\lolzy\OneDrive\Desktop\discordbot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\lolzy\OneDrive\Desktop\discordbot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\lolzy\OneDrive\Desktop\discordbot\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (events.js:376:20)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:19344) 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:19344) [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.
It says that the guild property is undefined, this might be because someone's using the command in DM's and that's why you're not getting the guild. So what you can do is add an if statement to check if the user is using the command in a server
Here's an example:
module.exports = {
name: "ticket",
aliases: [],
permissions: [],
description: "open a ticket!",
async execute(message, args, cmd, client, discord) {
if (!message.guild) return message.channel.send("You can't use this command in DM's");
// Rest of the code
}
};

Node js server crashes after PUT request

After making a put request, the app crashes with error
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
(node:21666) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(Use `node --trace-deprecation ...` to show where the warning was created)
Server up and running
(node:21666) DeprecationWarning: Mongoose: `findOneAndUpdate()` and `findOneAndDelete()` without the `useFindAndModify` option set to false are deprecated. See: https://mongoosejs.com/docs/deprecations.html#findandmodify
node:internal/process/promises:227
triggerUncaughtException(err, true /* fromPromise */);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:329:5)
at ServerResponse.setHeader (node:_http_outgoing:572:11)
at ServerResponse.header (/Users/kayode/Desktop/learn-mern/auth/node_modules/express/lib/response.js:771:10)
at ServerResponse.json (/Users/kayode/Desktop/learn-mern/auth/node_modules/express/lib/response.js:264:10)
at ServerResponse.send (/Users/kayode/Desktop/learn-mern/auth/node_modules/express/lib/response.js:158:21)
at /Users/kayode/Desktop/learn-mern/auth/routes/users.js:36:24
at processTicksAndRejections (node:internal/process/task_queues:94:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...
Here is my code...
const router = require('express').Router();
const User = require('../models/User')
router.put('/:email', async (req, res, next) => {
res.send(req.params._id)
let email = req.params.email;
let user = {
name: req.body.name,
email: req.body.email,
password: req.body.password
}
try {
await User.findOneAndUpdate(email, user);
res.status(200).send(JSON.stringify('200'));
console.log('Here first')
} catch (err) {
res.status(400).send(err) //not commented
}
})
module.exports = router;
But, if I try to make a another request (with postman), without refreshing the server it says sends a error could not send request
But then again, on line 36, "at /Users/kayode/Desktop/learn-mern/auth/routes/users.js:36:24" where it says res.status(400).send(err) //not commented
if I comment the line out (ie not return an error), the PUT request would be successful and another request after that would also work without refreshing or restartiung the server.
I know I can just comment that line out and move on, but I need to know what's happening, thanks!
You are sending the response in the beginning of the request and try to send it again in the end of the request (in line5) .
const router = require('express').Router();
const User = require('../models/User')
router.put('/:email', async (req, res, next) => {
let email = req.params.email;
let user = {
name: req.body.name,
email: req.body.email,
password: req.body.password
}
try {
await User.findOneAndUpdate(email, user);
res.status(200).send(JSON.stringify('200'));
console.log('Here first')
} catch (err) {
res.status(400).send(err) //not commented
}
})
module.exports = router;

chai and mocha showing test successful after error

I am using chai and mocha to test my REST API developed in NodeJS with typescript. I have written my test cases with mockgoose library to mock mongo db. When I run the first test case it successfully adds some data in database, but when I run the second and third test case it first shows Cannot set headers after they are sent to the client and later shows that the test is passed. I am not getting this workflow of execution how is it happening. Could anyone please explain.
My test case file looks like this :
process.env.NODE_ENV = 'TEST';
import { expect } from 'chai';
import request from 'supertest';
import app from '../app';
import * as mongodb from '../mongo/connection';
describe('Testing the API', () => {
before((done) => {
mongodb.connectMock()
.then(() => done())
.catch((err:any) => done(err))
})
it('OK, adding new employee', (done) => {
request(app).put('/add')
.send(<some JSON data>)
.then(res => {
...some matcher
done();
})
.catch(err => done(err));
})
it('OK, getting all employees', (done) => {
request(app).get('/all')
.then(res => {
...some matcher
done();
})
.catch(err => {
done(err)
});
})
it('OK, getting employee by ID', (done) => {
request(app)
.get(`/create/${id}`)
.then(res => {
...some matcher
done();
})
.catch(err => done(err));
})
})
and the controller file that produces the error is :
import { Request, Response } from 'express';
import Employee from '../models/Employee'
import { v4 as uuidv4 } from 'uuid';
export let allEmployee = (req: Request, res: Response) => {
Employee.find({})
.then(allEmployee => {
console.log('Getting all employee');
if(allEmployee.length > 0)
res.status(200).json(allEmployee);
console.log('Empty set of employees, please create');
res.status(404).json({ error: 'No employee found, please create', employee: allEmployee });
})
.catch((err:any) => {
console.log(err)
res.status(400).json({ error: err }); ****** I GET THE ERROR HERE ******
})
}
export let getEmployeeById = (req: Request, res: Response) => {
const employeeId: string = req.params.id;
Employee.find({ employeeId: employeeId })
.then(employee => {
console.log(`Getting employee with employee ID: ${employeeId}`);
if(employee.length > 0)
res.status(200).json(employee);
console.log(`No employee with employee ID: ${employeeId} found`);
res.status(404).json({ error: 'No employee found', employee: employee });
})
.catch(err => {
res.status(400).json({ error: err }); ****** I GET THE ERROR HERE ******
})
}
export let addEmployee = (req: Request, res: Response) => {
let employee = new Employee(<Some employee data in JSON>)
employee.save()
.then(employeeSaved => {
res.status(201).json({ message: 'New employee created!', employee: employeeSaved });
})
.catch(err => {
res.status(400).json({error:err});
})
}
The first test case that adds the employee to database works perfectly fine but when it does for second and third test case it shows error first and then successfully passes the test case.
It looks like :
Mock MongoDB Connected
✓ OK, adding new employee (69ms)
Getting all employees
Empty set of employees, please create
(node:16761) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:526:11)
at ServerResponse.header (/Users/abc/Downloads/some/git-test/some/Docker_Solution/node_modules/express/lib/response.js:771:10
)
at ServerResponse.send (/Users/abc/Downloads/some/git-test/some/Docker_Solution/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/Users/abc/Downloads/some/git-test/some/Docker_Solution/node_modules/express/lib/response.js:267:15)
at /Users/abc/Downloads/some/git-test/some/Docker_Solution/src/controllers/employeeController.ts:16:33
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:16761) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch bl
ock, 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-rej
ections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 9)
(node:16761) [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.
✓ OK, getting all employees
Getting employee with employee ID: 2b1e419e-57a7-4785-a3d7-96a1c786676b
No employee with employee ID: 2b1e419e-57a7-4785-a3d7-96a1c786676b found
(node:16761) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:526:11)
at ServerResponse.header (/Users/abc/Downloads/some/git-test/some/Docker_Solution/node_modules/express/lib/response.js:771:10)
at ServerResponse.send (/Users/abc/Downloads/some/git-test/some/Docker_Solution/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/Users/abc/Downloads/some/git-test/some/Docker_Solution/node_modules/express/lib/response.js:267:15)
at /Users/abc/Downloads/some/git-test/some/Docker_Solution/src/controllers/employeeController.ts:31:33
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:16761) 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: 10)
✓ OK, getting employee by ID
3 passing (1s)
Your problem seems to be your if conditions for res.status(200) or res.status(400) in both of your routes you have an issue with.
if(employee.length > 0)
res.status(200).json(employee);
console.log(`No employee with employee ID: ${employeeId} found`);
res.status(404).json({ error: 'No employee found', employee: employee });
should be and if(){} else{} because you are trying to send/alter the response again along with the 200 you already send
if(employee.length > 0) {
res.status(200).json(employee);
} else {
console.log(`No employee with employee ID: ${employeeId} found`);
res.status(404).json({ error: 'No employee found', employee: employee });
}

how can i parse a error message that i am getting in nodejs app

I am making an app with reactjs frontend and nodejs backend api for that at someplace i getting error something like this.
But here i want to get only this message email: {message: "This email is already taken", I tried to parse this error using some online turorial but when i try them i get error from backend.
This is the error after using errorparser
(node:14208) UnhandledPromiseRejectionWarning: ReferenceError: errors is not defined
at exports.default (C:/projects/bookworm-practice/bookworm-api/src/utils/parseErrors.js:5:15)
at C:/projects/bookworm-practice/bookworm-api/src/routes/users.js:14:54
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:14208) 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: 1)
(node:14208) [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.
this is my parseError function
import _ from 'lodash';
export default function () {
const result = {};
_.forEach(errors, (val, key) => {
result[key] = val.message;
});
return result;
}
this is my user function where i am using parseError
import express from 'express';
import User from '../models/User';
import parseErrors from '../utils/parseErrors';
const router = express.Router();
router.post('/', (req, res) => {
const { email, password } = req.body.user;
const user = new User({ email });
user.setPassword(password);
user.save()
.then(user => res.json({ user: user.toAuthJSON() }))
//.catch(err => res.json({ err })); // this is the default one
.catch(err => res.status(400).json({ errors: parseErrors(err.errors)
//this is after adding parseErrors funtion
}))
})
export default router;
Your parseErrors function did not includes errors as argument
import _ from 'lodash';
export default function (errors) {
const result = {};
_.forEach(errors, (val, key) => {
result[key] = val.message;
});
return result;
}

Resources