Rabbitmq Socket closed abruptly during opening handshake - javascript

Creating a chat server.
However, when I send a message, it goes into the queue, but then mysql doesn't have data. I think the server is turning on, but I keep getting an error like Socket closed absolutely during opening handshake Help me
consumer.js
`
Consumer: async () => {
try {
const connect = await amqp.connect(amqpURL);
const ch = await connect.createChannel();
const queue = "queue";
await ch.assertQueue(queue, async (message) => {
console.log(message.value.toString());
});
arr.push(JSON.parse(message.value.toString()));
console.log(arr);
if (arr.length == 5) {
try {
const rows = await chatting
.bulkCreate(arr, { hooks: true })
.catch((err) => {
console.log(err);
});
arr.splice(0);
console.log(rows);
return;
} catch (err) {
console.log(err);
}
ch.ack(message);
}
} catch (err) {
console.log(err);
}
},
app.js
`
const express = require("express");
const app = express();
const cors = require("cors");
const http = require("http");
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const { chatting, sequelize } = require("./models");
const rabbitmq = require("./rabbit");
//const consumer = require("./consumer");
const amqp = require("amqplib");
const amqpURL = "amqp://localhost:5672";
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cors());
sequelize
.sync({ force: false })
.then(() => {
console.log("연결됨");
})
.catch((err) => {
console.log(err);
});
const send = async (message) => {
try {
console.log(message);
const connect = await amqp.connect(amqpURL);
const channel = await connect.createChannel();
const exchange = "exchange";
const queue = "queue";
const routingkey = "sample.routing";
await channel
.assertExchange(exchange, "direct", { durable: true })
.catch((err) => console.log(err));
await channel.assertQueue(queue, { durable: true });
await channel.bindQueue(queue, exchange, routingkey);
await channel.publish(exchange, routingkey, Buffer.from(message));
} catch (err) {
console.log(err);
}
};
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.get("/test", async (req, res) => {
try {
const { idx } = req.body;
const rows = await chatting.findOne({ idx: idx });
if (rows) return res.status(200).json({ result: rows });
} catch (err) {
console.log(err);
}
});
io.on("connection", (socket) => {
console.log("connect");
socket.on("disconnect", () => {
console.log("disconnect");
});
});
io.emit("some event", {
someProperty: "some value",
otherProperty: "other value",
});
io.on("connection", (socket) => {
socket.on("chat message", async (message) => {
try {
await send(JSON.stringify(message));
io.emit("chat message", message);
console.log(message);
} catch (err) {
console.log(err);
}
});
});
server.listen(2022, () => {
console.log("listening on :2022");
});
rabbitmq.Consumer();
`
`
pic
enter image description here
I tried many things and I want to solve
Error: Socket closed abruptly during opening handshake
at Socket.endWhileOpening
this error

Related

Await function doesn't work with mongo DB collections

I'm having trouble capturing the current collection in mongodb.
I have a file with FetchUsers function which returns a collection with users:
const mongoose = require('mongoose');
const uri = "mongodb+srv://<username>:<password>#<cluster-url>.sdzp0ug.mongodb.net/?
retryWrites=true&w=majority";
const fetchUsers= () => {
const connectionParams = {
useNewUrlParser: true,
useUnifiedTopology: true,
}
try{
mongoose.connect(uri);
} catch (error)
{
console.log(error);
}
const collectionName = 'UsersTests'
const Users = mongoose.model(collectionName, new mongoose.Schema({}));
Users .find({}, function(err, docs) {
if (err) {
console.error(err);
return;
}
console.log(`Documents in ${collectionName}:`);
mongoose.connection.close();
console.log(`My current collection: ${docs}`);
return docs;
});
}
module.exports = fetchUsers
In another file I have a function that takes the returned value and then displays it:
const fetchData = require("../../controllers/USersControllers/fetchUsers.js");
async function displayUsers() {
let users = await fetchData();
console.log(users);
}
module.exports = displayUsers;
and all this is running on the express server
const express = require("express");
const displayUsers = require("./public/js/displayUsers.js");
const app = express();
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.listen(5000, () => {
console.log("Server started on port 3000");
displayUsers();
});
The problem is that displayUsers displays undefined and doesn't wait until fetchData returns a collection.
OK, I corrected the code and it works.
GetUsersModel.js:
const mongoose = require("mongoose");
const uri =
"mongodb+srv://<username>:<password>#<cluster-url>.sdzp0ug.mongodb.net/?
retryWrites=true&w=majority";
const connectionParams = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
try {
mongoose.connect(
uri
);
console.log("Database conected!");
} catch (error) {
console.log(error);
console.log("Database connection failed");
}
const Schema = new mongoose.Schema({
content: String,
title: String,
author: String,
});
const Users =
mongoose.model.userTest ||
mongoose.model("userTest", Schema);
module.exports = Users;
fetchUsersData.js
const mongoose = require('mongoose');
const Users =
require("../controllers/SnippetsControllers/GetSnippetModel.js");
const uri =
"mongodb+srv://<username>:<password>#<cluster-url>.sdzp0ug.mongodb.net/?
retryWrites=true&w=majority";
const fetchUsers = () => {
const connectionParams = {
useNewUrlParser: true,
useUnifiedTopology: true,
}
try{
mongoose.connect(uri);
console.log('Database conected!!!!!')
} catch (error)
{
console.log(error);
console.log('Database connection failed')
}
return new Promise((resolve, reject) => {
Users.find({}, function(err, docs) {
if (err) {
reject(err);
} else {
resolve(docs);
}
});
});
}
module.exports = fetchUsers;
UseUsersData.js
const fetchData = require("../models/fetchUsersData");
async function displayUsers(req) {
let usersContainer = [];
try {
let users = await fetchData();
let usersArray = users;
console.log(usersArray);
} catch (error) {
console.log(error);
}
}

(Node)Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

I have been learninng NodeJS and mongoDB by youtube, but unfortunately i faced with this problem, and here is my code file! thank you in advance!
db.js
const { MongoClient } = require("mongodb");
let dbConnection;
module.exports = {
connectToDb: (cb) => {
MongoClient.connect("mongodb://localhost:27017/bookstore")
.then((res) => {
dbConnection = res.db();
return cb();
})
.catch((error) => {
console.log(error);
return cb(error);
});
},
getDb: () => dbConnection,
};
index.js
const express = require("express");
const { connectToDb, getDb } = require("./db");
// init app and middleware
const app = express();
//db connection
let db;
connectToDb((xato) => {
if (!xato) {
app.listen(3000, () => {
console.log("The 3000 port is installed");
});
db = getDb();
return db;
}
});
//routes
app.get("/bookstore", (req, res) => {
let mybook = [];
// the collection name from mongoDB
db.collection("bookstore")
.find()
.sort({ author: 1 })
.forEach((book) => mybook.push(book))
.then(() => {
return res.sendStatus(200).json(mybook);
})
.catch(() => {
return res.sendStatus(500).send("there were an error");
});
// res.json({ MyWords: "I am coming from json res" });
});
it must return data from local mongodb database. But it is facing with the problem. Please give me a solution!
both .sendStatus and .json will try to response to client. So the second call will result in this error.
Just use res.json(mybook) and res.send("there were an error") is enough.
In case you want to maintain status code and also send data. Use res.status(500).send("there were an error").

FATAL:zygote_host_impl_linux.cc(117)] No usable sandbox! puppeter

I am using puppeteer in the following project https://github.com/gatwirival/Whatsapp-api.git .It's working fine locally but during deployment in Heroku, it runs for a little while then crashes with the following error FATAL:zygote_host_impl_linux.cc(117)] No usable sandbox!
App.js
const express = require('express');
const puppeteer = require("puppeteer");
const fs = require('fs');
const createError = require('http-errors');
const morgan = require('morgan');
const { Client } = require('whatsapp-web.js');
require('dotenv').config();
const app = express();
const SESSION_FILE_PATH = './session.json';
let sessionCfg;
if (fs.existsSync(SESSION_FILE_PATH)) {
sessionCfg = require(SESSION_FILE_PATH);
}
const client = new Client({
puppeteer: { headless: false }, // Make headless true or remove to run browser in background
session: sessionCfg,
});
client.initialize();
client.on('qr', qr => {
// NOTE: This event will not be fired if a session is specified.
console.log('QR RECEIVED', qr);
app.get('/getqr', (req, res, next) => {
res.send({ qr });
});
});
client.on('authenticated', session => {
console.log('AUTHENTICATED', session);
sessionCfg = session;
fs.writeFile(SESSION_FILE_PATH, JSON.stringify(session), function (err) {
if (err) {
console.error(err);
}
});
});
client.on('auth_failure', msg => {
// Fired if session restore was unsuccessfull
console.error('AUTHENTICATION FAILURE', msg);
});
client.on('ready', () => {
console.log('READY');
});
// Run `npm i qrcode-terminal` before this
const qrcode = require('qrcode-terminal')
client.on('qr', qr => {
// NOTE: This event will not be fired if a session is specified.
console.log('QR RECEIVED', qr);
qrcode.generate(qr, { small: true });
app.get('/getqr', (req, res, next) => {
res.send({ qr });
});
});
app.post('/sendmessage', async (req, res, next) => {
try {
// Magic happens here
} catch (error) {
next(error)
}
})
app.post('/sendmessage', async (req, res, next) => {
try {
const { number, message } = req.body; // Get the body
const msg = await client.sendMessage(`${number}#c.us`, message); // Send the message
res.send({ msg }); // Send the response
} catch (error) {
next(error);
}
});
//puppeter
app.listen(process.env.PORT || 3000, function(){
const browser = puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox'],
});
app.get("/", (req, res) => {
let page;
(async () => {
page = await (await browser).newPage();
await page.setContent(`<p>web running at ${Date()}</p>`);
res.send(await page.content());
})()
.catch(err => res.sendStatus(500))
.finally(async () => await page.close())
;
});
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
What I have tried:
Added the following code snippet and yet I get the error
const browser = puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox'],
});
After this failed I tried this.
-sudo sysctl -w kernel.unprivileged_userns_clone=1
to access the sandbox of chromium.

Route.post() requires a callback function but got a [object Undefined]? Why am I getting this error?

I'm working on the backend of my react project and I seem to be having some trouble with the backend for the info. When I do npm start I get an error saying Route.post() requires a callback function but got a [object Undefined] and I'm confused as to why.
Here is my server.js file
const express = require("express");
const cors = require("cors");
const dbConfig = require("./app/config/db.config");
const app = express();
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
const db = require("./app/models");
const Role = db.role;
db.mongoose
.connect(`mongodb+srv://tami00:MEUxClWqUNbLz359#cluster0.gmvao.mongodb.net/test?retryWrites=true&w=majority`, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Successfully connect to MongoDB.");
initial();
})
.catch(err => {
console.error("Connection error", err);
process.exit();
});
// simple route
app.use('/favourite', require('.app/routes/favourite.routes'));
// routes
// require(".app/routes/favourite.routes")(app);
require("./app/routes/auth.routes")(app);
require("./app/routes/user.routes")(app);
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
function initial() {
Role.estimatedDocumentCount((err, count) => {
if (!err && count === 0) {
new Role({
name: "user"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'user' to roles collection");
});
new Role({
name: "creator"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'creator' to roles collection");
});
new Role({
name: "watcher"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'watcher' to roles collection");
});
}
});
}
and here is my favourite.routes.js file. I have no issue with the other 2 routes.
const express = require('express');
const router = express.Router();
const{Favourite} = require("../models/favourite.model");
const {auth} = require("../middlewares/authJwt");
router.post("/favouriteNumber", auth, (req, res) => {
Favourite.find({"movieId": req.body.movieId})
.exec((err, favourite) => {
if(err) return res.status(400).send(err)
res.status(200).json({success: true, favouriteNumber: favourite.length})
})
})
router.post("/favourited", auth, (req, res) => {
Favourite.find({"movieId": req.body.movieId, "userFrom": req.body.userFrom})
.exec((err, favourite) => {
if(err) return res.status(400).send(err)
let result = false;
if(favourite.length !== 0) {
result = true
}
res.status(200).json({success: true, favourited: result});
})
})
router.post("/addToFavourite", auth, (req, res) => {
const favourite = new Favourite(req.body)
favourite.save((err, doc) => {
if(err) return res.json({success: false, err})
return res.status(200).json({success: true, doc})
})
})
router.post("/removeFavorite", auth, (req, res) => {
Favourite.findOneAndDelete({movieId: req.body.movieId, userFrom: req.body.userFrom})
.exec((err, doc) => {
if(err) return res.json({success: false, err})
return res.status(200).json({success: true, doc})
})
})
module.exports = router;
This is the favourite models where I'm creating the mongoose schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const favSchema = mongoose.Schema({
userFrom: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
movieId : {
type: String
},
movieTitle : {
type: String
},
movieImg : {
type: String
}
})
const Favourite = mongoose.model('Favourite', favSchema);
module.exports = {Favourite}
Heres the middlewares auth file
const jwt = require("jsonwebtoken");
const config = require("../config/auth.config.js");
const db = require("../models");
const User = db.user;
const Role = db.role;
verifyToken = (req, res, next) => {
let token = req.headers["x-access-token"];
if (!token) {
return res.status(403).send({ message: "No token provided!" });
}
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
return res.status(401).send({ message: "Unauthorized!" });
}
req.userId = decoded.id;
next();
});
};
isAdmin = (req, res, next) => {
User.findById(req.userId).exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
Role.find(
{
_id: { $in: user.roles }
},
(err, roles) => {
if (err) {
res.status(500).send({ message: err });
return;
}
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === "admin") {
next();
return;
}
}
res.status(403).send({ message: "Require Admin Role!" });
return;
}
);
});
};
isModerator = (req, res, next) => {
User.findById(req.userId).exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
Role.find(
{
_id: { $in: user.roles }
},
(err, roles) => {
if (err) {
res.status(500).send({ message: err });
return;
}
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === "moderator") {
next();
return;
}
}
res.status(403).send({ message: "Require Moderator Role!" });
return;
}
);
});
};
const authJwt = {
verifyToken,
isAdmin,
isModerator
};
module.exports = authJwt;
const {auth} = require("../middlewares/authJwt"); uses destructuring, but your exports from ../middlewares/authJwt don't have a field auth.
auth therefore is undefined.

MongoDB with node.js trying to make a new file (JavaScript)

I wrote a little of code to start learning MongoDB with Node.js in JavaScript but it doesn't work but it doesn't
give a error while running probably someone can help me with that.
The Main code:
const mongoose = require('mongoose');
const express = require('express');
const test = express();
const Blog = require('./bdSchema');
//connec to mongodb
const dbURI = 'mongodb+srv://Carsten:<int the real code the password is here>#cluster0.w6iwv.mongodb.net/tomhatesgeschaft?retryWrites=true&w=majority';
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then((result) => console.log("connected to db"))
.catch((err) => console.log(err))
test.get('/add-tomhatesgeschaft', (req, res) => {
const tomhatesgeschaft = new Blog({
title: 'hi'
});
tomhatesgeschaft.save()
.then((result) => {
res.send(result)
})
.catch((err) => {
console.log(err);
});
})
The BDSchema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BDSchema = new Schema({
title: {
type: String,
required: true,
},
});
const Blog = mongoose.model('Blog', BDSchema);
module.exports = Blog;
In your Node.js code, change the save function as below.
tomhatesgeschaft.save((err,result) => {
if (err){
console.error(err);
}
else{
res.send(result)
})
})
OR
test.get('/add-tomhatesgeschaft', async (req, res) => {
const tomhatesgeschaft = new Blog({
title: 'hi'
});
try {
await tomhatesgeschaft.save()
} catch(error) {
console.error(error)
}
})
PS: You should not use GET requests for operations such as saving data to the database. Ideally, you should use a POST request.
Example with async:
test.post('/add-tomhatesgeschaft', async (req, res) => {
const tomhatesgeschaft = new Blog({
title: 'hi'
});
try {
await tomhatesgeschaft.save()
} catch(error) {
console.error(error)
}
})

Categories

Resources