My post request req.body turns empty on Heroku - javascript

My post request to create new item, turns me with new item created. It is working well in localhost.
But when I deploy my app on heroku and then post request Status Code: 503 Service Unavailable , but empty res.body. Here also my server.js file
server.js
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const app = express();
const items = require("./routes/api/items");
const users = require("./routes/api/user");
const auth = require("./routes/api/auth");
app.use(express.json());
require("dotenv").config();
mongoose.connect(process.env.MONGO_DB).then(console.log("connected"));
app.use(cors());
app.use("/api/items", items);
app.use("/api/users", users);
app.use("/api/auth", auth);
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
const listener = app.listen(process.env.PORT || 5000, () => {
console.log("Your app is listening on port " + listener.address().port);
});
item.js
router.post("/createTeam", auth, (req, res) => {
const newItem = new Item({
name: req.body.name,
});
newItem.save(function (err, result) {
if (err) {
console.log(err);
} else {
res.json(result);
}
});
});
itemActions.js
export const addItems = (input) => (dispatch, getState) => {
axios
.post("/api/items/createTeam", input, tokenConfig(getState))
.then((res) =>
dispatch({
type: ADD_ITEM,
payload: res.data,
})
)
.catch((err) =>
dispatch(
returnErrors(err.response.data, err.response.status, "GET_ERRORS")
)
);
};
Also my heroku logs are here when I create new Team
2021-12-04T09:51:55.743015+00:00 app[web.1]: MongoWriteConcernError: No write concern mode named 'majority\"' found in replica set configuration
2021-12-04T09:51:55.743023+00:00 app[web.1]: at MessageStream.messageHandler (/app/node_modules/mongodb/lib/cmap/connection.js:463:30)
2021-12-04T09:51:55.743024+00:00 app[web.1]: at MessageStream.emit (events.js:400:28)
2021-12-04T09:51:55.743024+00:00 app[web.1]: at processIncomingData (/app/node_modules/mongodb/lib/cmap/message_stream.js:108:16)
2021-12-04T09:51:55.743024+00:00 app[web.1]: at MessageStream._write (/app/node_modules/mongodb/lib/cmap/message_stream.js:28:9)
2021-12-04T09:51:55.743025+00:00 app[web.1]: at writeOrBuffer (internal/streams/writable.js:358:12)
2021-12-04T09:51:55.743026+00:00 app[web.1]: at MessageStream.Writable.write (internal/streams/writable.js:303:10)
2021-12-04T09:51:55.743026+00:00 app[web.1]: at TLSSocket.ondata (internal/streams/readable.js:731:22)
2021-12-04T09:51:55.743026+00:00 app[web.1]: at TLSSocket.emit (events.js:400:28)
2021-12-04T09:51:55.743027+00:00 app[web.1]: at addChunk (internal/streams/readable.js:293:12)
2021-12-04T09:51:55.743027+00:00 app[web.1]: at readableAddChunk (internal/streams/readable.js:267:9) {
2021-12-04T09:51:55.743028+00:00 app[web.1]: code: 79,
2021-12-04T09:51:55.743030+00:00 app[web.1]: codeName: 'UnknownReplWriteConcern',
2021-12-04T09:51:55.743030+00:00 app[web.1]: errInfo: {
2021-12-04T09:51:55.743031+00:00 app[web.1]: writeConcern: { w: 'majority"', wtimeout: 0, provenance: 'clientSupplied' }
2021-12-04T09:51:55.743031+00:00 app[web.1]: },
2021-12-04T09:51:55.743032+00:00 app[web.1]: result: {
2021-12-04T09:51:55.743032+00:00 app[web.1]: n: 1,
2021-12-04T09:51:55.743032+00:00 app[web.1]: opTime: { ts: new Timestamp({ t: 1638611515, i: 13 }), t: 104 },
2021-12-04T09:51:55.743033+00:00 app[web.1]: electionId: new ObjectId("7fffffff0000000000000068"),
2021-12-04T09:51:55.743033+00:00 app[web.1]: ok: 1,
2021-12-04T09:51:55.743034+00:00 app[web.1]: writeConcernError: {
2021-12-04T09:51:55.743034+00:00 app[web.1]: code: 79,
2021-12-04T09:51:55.743034+00:00 app[web.1]: codeName: 'UnknownReplWriteConcern',
2021-12-04T09:51:55.743035+00:00 app[web.1]: errmsg: `No write concern mode named 'majority\\"' found in replica set configuration`,
2021-12-04T09:51:55.743035+00:00 app[web.1]: errInfo: [Object]
2021-12-04T09:51:55.743036+00:00 app[web.1]: },
2021-12-04T09:51:55.743036+00:00 app[web.1]: '$clusterTime': {
2021-12-04T09:51:55.743036+00:00 app[web.1]: clusterTime: new Timestamp({ t: 1638611515, i: 13 }),
2021-12-04T09:51:55.743036+00:00 app[web.1]: signature: [Object]
2021-12-04T09:51:55.743037+00:00 app[web.1]: },
2021-12-04T09:51:55.743037+00:00 app[web.1]: operationTime: new Timestamp({ t: 1638611515, i: 13 })
2021-12-04T09:51:55.743037+00:00 app[web.1]: }
2021-12-04T09:51:55.743037+00:00 app[web.1]: }
SOLUTION
I removed '' or "" from MONGO_DB which is on heroku config vars, and solved

Related

8Cant deploy Nodejs server in Heroku : 'Error: Cannot find module 'getStream''

My project seems to have no issues when running locally, but when I try to deploy it in heroku and open the app it gives me an application error. I tried checking the logs in heroku and this is what I get.
2022-09-14T20:31:10.475090+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1028:19)
2022-09-14T20:31:10.475091+00:00 app[web.1]: at require (node:internal/modules/cjs/helpers:102:18)
2022-09-14T20:31:10.475091+00:00 app[web.1]: at Object.<anonymous> (/app/controllers/auth.js:1:19)
2022-09-14T20:31:10.475092+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1126:14)
2022-09-14T20:31:10.475092+00:00 app[web.1]: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
2022-09-14T20:31:10.475092+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:1004:32)
2022-09-14T20:31:10.475093+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:839:12)
2022-09-14T20:31:10.475093+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1028:19) {
2022-09-14T20:31:10.475093+00:00 app[web.1]: code: 'MODULE_NOT_FOUND',
2022-09-14T20:31:10.475094+00:00 app[web.1]: requireStack: [
2022-09-14T20:31:10.475094+00:00 app[web.1]: '/app/controllers/auth.js',
2022-09-14T20:31:10.475094+00:00 app[web.1]: '/app/routes/auth.js',
2022-09-14T20:31:10.475095+00:00 app[web.1]: '/app/index.js'
2022-09-14T20:31:10.475095+00:00 app[web.1]: ]
2022-09-14T20:31:10.475095+00:00 app[web.1]: }
2022-09-14T20:31:10.660749+00:00 heroku[web.1]: Process exited with status 1
2022-09-14T20:31:10.723193+00:00 heroku[web.1]: State changed from starting to crashed
2022-09-14T20:31:10.726441+00:00 heroku[web.1]: State changed from crashed to starting
2022-09-14T20:31:13.020405+00:00 heroku[web.1]: Starting process with command `npm start`
2022-09-14T20:31:16.234548+00:00 app[web.1]:
2022-09-14T20:31:16.234562+00:00 app[web.1]: > server#1.0.0 start
2022-09-14T20:31:16.234562+00:00 app[web.1]: > node index.js
2022-09-14T20:31:16.234563+00:00 app[web.1]:
2022-09-14T20:31:16.387441+00:00 app[web.1]: node:internal/modules/cjs/loader:959
2022-09-14T20:31:16.387443+00:00 app[web.1]: throw err;
2022-09-14T20:31:16.387444+00:00 app[web.1]: ^
2022-09-14T20:31:16.387444+00:00 app[web.1]:
2022-09-14T20:31:16.387444+00:00 app[web.1]: Error: Cannot find module 'getStream'
2022-09-14T20:31:16.387445+00:00 app[web.1]: Require stack:
2022-09-14T20:31:16.387445+00:00 app[web.1]: - /app/controllers/auth.js
2022-09-14T20:31:16.387446+00:00 app[web.1]: - /app/routes/auth.js
2022-09-14T20:31:16.387446+00:00 app[web.1]: - /app/index.js
2022-09-14T20:31:16.387446+00:00 app[web.1]: at Function.Module._resolveFilename (node:internal/modules/cjs/loader:956:15)
2022-09-14T20:31:16.387447+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:804:27)
2022-09-14T20:31:16.387447+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1028:19)
2022-09-14T20:31:16.387448+00:00 app[web.1]: at require (node:internal/modules/cjs/helpers:102:18)
2022-09-14T20:31:16.387448+00:00 app[web.1]: at Object.<anonymous> (/app/controllers/auth.js:1:19)
2022-09-14T20:31:16.387448+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1126:14)
2022-09-14T20:31:16.387449+00:00 app[web.1]: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
2022-09-14T20:31:16.387449+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:1004:32)
2022-09-14T20:31:16.387449+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:839:12)
2022-09-14T20:31:16.387449+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1028:19) {
2022-09-14T20:31:16.387450+00:00 app[web.1]: code: 'MODULE_NOT_FOUND',
2022-09-14T20:31:16.387450+00:00 app[web.1]: requireStack: [
2022-09-14T20:31:16.387450+00:00 app[web.1]: '/app/controllers/auth.js',
2022-09-14T20:31:16.387450+00:00 app[web.1]: '/app/routes/auth.js',
2022-09-14T20:31:16.387451+00:00 app[web.1]: '/app/index.js'
2022-09-14T20:31:16.387451+00:00 app[web.1]: ]
2022-09-14T20:31:16.387451+00:00 app[web.1]: }
2022-09-14T20:31:16.528452+00:00 heroku[web.1]: Process exited with status 1
2022-09-14T20:31:16.728856+00:00 heroku[web.1]: State changed from starting to crashed
2022-09-14T20:31:55.119571+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET pad="190.237.25.187" dyno= connect= service= status=503 bytes= protocol=https2022-09-14T20:42:01.202592+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=file-iu-sys.herokuapp.com request_id=b157556e-1a74-4d16-aef5-7e2e8cea2612 fwd="190.237.25.187" dyno= connect= service= status=503 bytes= protocol=https 2022-09-14T20:42:02.113418+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=file-iu-sys.herokuapp.com request_id=2c0cf996-5b33-4d15-b7c6-88cedd9f9c25 fwd="190.237.25.187" dyno= connect= service= status=503 bytes= protocol=https
I have tried checking for missing scripts, changing the Port to process.env.PORT, heroku repo:reset, deleting the git file and starting a new git init and even deleting the node_modules folder and running npm install. A similar app I tried hosting in heroku seems to run with no problems, the difference being this one has a mysql dependency and the heroku app has a clearDB plugin. The 'getstream' version is '8.0.1' (the one that runs without problems is '8.0.0' could that be the issue?).
this is my package.json file:
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.0.1",
"body-parser": "^1.20.0",
"cors": "^2.8.5",
"crypto": "^1.0.1",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"getstream": "^8.0.1",
"mysql": "^2.18.1",
"nodemon": "^2.0.16",
"stream-chat": "^6.5.1"
}
}
index.js file:
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const bodyParser = require('body-parser')
const authRoutes = require('./routes/auth.js')
const connection = mysql.createPool({
host: '*host-name*',
user: '*user*',
password: '*password*',
database: '*database*'
})
const app = express();
const PORT = process.env.PORT || 3001;
require('dotenv').config();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded());
//Routes
app.use('/auth', authRoutes);
app.get('/', (req, res) =>{
res.send('Server an')
})
//DB connection
//get from DB
app.get('/api/get', (req, res)=>{
const sqlSelect = 'SELECT * FROM anmeldungen';
connection.query(sqlSelect, (err, result)=>{
res.send(result);
if(err){
console.log('Error fetching from db');
}
});
})
//write to DB
app.use(bodyParser.urlencoded({extended: true}));
app.post('/api/insert', (req, res)=>{
const Student = req.body.Student;
const Fach = req.body.Fach;
//const Datum = req.body.Datum;
const Datum = new Date().toISOString().split('T')[0];
const DateiName = req.body.DateiName;
const Seite = req.body.Seite;
const Beschreibung = req.body.Beschreibung;
const sqlInsert = 'INSERT INTO anmeldungen(Student, Fach, Datum, DateiName, Seite, Beschreibung) VALUES(?,?,?,?,?,?)'
connection.query(sqlInsert, [Student, Fach, Datum, DateiName, Seite, Beschreibung], (err, result)=>{
console.log(result);
});
});
//delete from db
app.delete('/api/delete/:id', (req, res) =>{
const rowId = req.params.id;
const sqlDelete = "DELETE FROM anmeldungen WHERE id = ?";
connection.query(sqlDelete, rowId, (err, result)=>{
if(err) console.log(err);
})
})
//update rows in db
app.put('/api/update/:id', (req, res) =>{
const rowId = req.params.id;
const rowStat = req.body.Status;
const sqlUpdate = "UPDATE anmeldungen SET Status = ? WHERE id = ?";
connection.query(sqlUpdate, [rowStat, rowId], (err, result)=>{
if(err) console.log(err);
})
})
app.listen(PORT, () => console.log(`Server lauft auf port ${PORT}`));
auth.js:
const {connect} = require('getStream');
const bcrypt = require('bcrypt');
const StreamChat = require('stream-chat').StreamChat;
const crypto = require('crypto');
require('dotenv').config();
const api_key = process.env.STREAM_API_KEY;
const api_secret = process.env.STREAM_API_SECRET;
const app_id = process.env.STREAM_APP_ID;
const signup = async (req, res) => {
try {
//get from the front-end
const {fullName, username, password, phoneNumber} = req.body;
//create a random user Id: 16 digits in hexadecimal
const userId = crypto.randomBytes(16).toString('hex');
//connection to stream
const serverClient = connect(api_key, api_secret, app_id);
//create a password for the user token
const hashedPassword = await bcrypt.hash(password, 10);
//create token for the user
const token = serverClient.createUserToken(userId);
//get the values straight from the front-end to ensure secure authentication
res.status(200).json({token, fullName, username, userId, hashedPassword, phoneNumber})
} catch (error) {
console.log(error);
res.status(500).json({message: error});
}
};
const login = async(req, res) => {
try {
const {username, password} = req.body;
const serverClient = connect(api_key, api_secret, app_id);
//new instance of streamChat
const client = StreamChat.getInstance(api_key, api_secret);
//query all users that match this username
const {users} = await client.queryUsers({name: username});
if(!users.length) return res.status(400).json({message: 'Benutzername nicht gefunden.'});
//decrypt the password to see if it matches
const success = await bcrypt.compare(password, users[0].hashedPassword);
//create new token for this specific user's id.
const token = serverClient.createUserToken(users[0].id);
if(success){
res.status(200).json({token, fullName: users[0].fullName, username, userId: users[0].id});
} else {
res.status(500).json({message: 'falsches Kennwort'});
}
} catch (error) {
console.log(error);
res.status(500).json({message: error});
}
};
module.exports = {signup, login}
Found the problem in the auth.js file: I had written const {connect} = require('getStream'); instead of const {connect} = require('getstream');. So I guess it was due to naming conventions in a way. #Chris ty, that first question was right on the money.

Can't use and connect to MongoDB

So, I am building a small URL shortener project with js, express, and MongoDB but, I got errors when I'm trying to run my local server and I can't connect to MongoDB!
This is my code:
const express = require('express')
const mongoose = require('mongoose')
const ShortUrl = require('./models/shortUrl')
const app = express();
mongoose.connect('mongodb://localhost/urlShortener', {
useNewUrlParser: true, useUnifiedTopology: true
})
app.set('view engine', 'ejs')
app.use(express.urlencoded({ extended: false}))
app.get('/', async (req, res) => {
const shortUrls = await ShortUrl.find()
res.render('index', { shortUrls: shortUrls })
});
app.post('/shortUrls', async (req, res) => {
await ShortUrl.create({ full: req.body.fullUrl })
res.redirect('/')
})
app.get('/:shortUrl', async (req, res) => {
const shortUrl = await ShortUrl.findOne({ short: req.params.shortUrl })
if (shortUrl == null) return res.sendStatus(404)
shortUrl.clicks++
shortUrl.save()
res.redirect(shortUrl.full)
})
app.listen(process.env.PORT || 5000);
And this is the full log:
[nodemon] 2.0.15
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\connection.js:807
const serverSelectionError = new ServerSelectionError();
^
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at NativeConnection.Connection.openUri (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\connection.js:807:32)
at C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\index.js:342:10
at C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\index.js:1176:10)
at Mongoose.connect (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\index.js:341:20)
at Object.<anonymous> (C:\Users\apsoltanian-pc\Documents\js\url-shortener\server.js:6:10)
at Module._compile (node:internal/modules/cjs/loader:1099:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
_hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 1096791,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongodb\lib\cmap\connect.js:381:20)
at Socket.<anonymous> (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongodb\lib\cmap\connect.js:301:22)
at Object.onceWrapper (node:events:642:26)
at Socket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
}
}
Node.js v17.7.2
[nodemon] app crashed - waiting for file changes before starting...
Thank u guys =)
I was trying to start the small URL-shortener project that I wrote in js, express, and MongoDB but, the problem is that I can't connect to my MongoDB database :(
I solved the problem, so, I replaced localhost with 127.0.0.1 in the connection string and now my problem is solved!
it is because of some ipv6 configurations...
Thank u :)

Is there a way to disable security on heroku Postgres db?

My project doesn't involve any private information, so I don't care about vulnerabilities.
I am certain that the connection between the App/server and the DB is the problem.
I tried to looking on Youtube and on Google, but the answers were outdated or they just didn't work for me. However, connecting to the database with heroku psql (cli) or connecting with pgAdmin4 using db creds and querying, creating tables works fine.
Following this guy's tutorial
https://github.com/ousecTic/pern-deploy-tutorial
Errors:
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: true,
});
------------------------------------------------------------------------
2022-02-12T11:02:33.058860+00:00 heroku[web.1]: State changed from starting to up
2022-02-12T11:02:34.275213+00:00 app[web.1]: node:internal/process/promises:265
2022-02-12T11:02:34.275240+00:00 app[web.1]: triggerUncaughtException(err, true /* fromPromise */);
2022-02-12T11:02:34.275241+00:00 app[web.1]: ^
2022-02-12T11:02:34.275241+00:00 app[web.1]:
2022-02-12T11:02:34.275241+00:00 app[web.1]: Error: self signed certificate
2022-02-12T11:02:34.275242+00:00 app[web.1]: at TLSSocket.onConnectSecure (node:_tls_wrap:1530:34)
2022-02-12T11:02:34.275242+00:00 app[web.1]: at TLSSocket.emit (node:events:520:28)
2022-02-12T11:02:34.275242+00:00 app[web.1]: at TLSSocket._finishInit (node:_tls_wrap:944:8)
2022-02-12T11:02:34.275243+00:00 app[web.1]: at TLSWrap.ssl.onhandshakedone (node:_tls_wrap:725:12) {
2022-02-12T11:02:34.275243+00:00 app[web.1]: code: 'DEPTH_ZERO_SELF_SIGNED_CERT'
2022-02-12T11:02:34.275243+00:00 app[web.1]: }
-------------------------------------------------------------------------
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
------------------------------------------------------------------------------------
2022-02-12T11:19:13.660398+00:00 app[web.1]: { description: 'jhoipjo' } <<console.log()
2022-02-12T11:19:13.681933+00:00 app[web.1]: no pg_hba.conf entry for host "3.86.151.70", user "user", database "database", SSL off
------------------------------------------------------------------------------------
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: false,
});
------------------------------------------------------------------------------------
2022-02-12T11:58:50.711988+00:00 app[web.1]: /app/node_modules/pg-protocol/dist/parser.js:287
2022-02-12T11:58:50.712007+00:00 app[web.1]: const message = name === 'notice' ? new messages_1.NoticeMessage(length, messageValue) : new messages_1.DatabaseError(messageValue, length, name);
2022-02-12T11:58:50.712008+00:00 app[web.1]: ^
2022-02-12T11:58:50.712009+00:00 app[web.1]:
2022-02-12T11:58:50.712010+00:00 app[web.1]: error: no pg_hba.conf entry for host "3.236.98.211", user "user", database "database", SSL off
2022-02-12T11:58:50.712010+00:00 app[web.1]: at Parser.parseErrorMessage (/app/node_modules/pg-protocol/dist/parser.js:287:98)
2022-02-12T11:58:50.712011+00:00 app[web.1]: at Parser.handlePacket (/app/node_modules/pg-protocol/dist/parser.js:126:29)
2022-02-12T11:58:50.712012+00:00 app[web.1]: at Parser.parse (/app/node_modules/pg-protocol/dist/parser.js:39:38)
2022-02-12T11:58:50.712013+00:00 app[web.1]: at Socket.<anonymous> (/app/node_modules/pg-protocol/dist/index.js:11:42)
2022-02-12T11:58:50.712014+00:00 app[web.1]: at Socket.emit (node:events:520:28)
2022-02-12T11:58:50.712014+00:00 app[web.1]: at addChunk (node:internal/streams/readable:315:12)
2022-02-12T11:58:50.712014+00:00 app[web.1]: at readableAddChunk (node:internal/streams/readable:289:9)
2022-02-12T11:58:50.712014+00:00 app[web.1]: at Socket.Readable.push (node:internal/streams/readable:228:10)
2022-02-12T11:58:50.712015+00:00 app[web.1]: at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
2022-02-12T11:58:50.712015+00:00 app[web.1]: length: 166,
2022-02-12T11:58:50.712016+00:00 app[web.1]: severity: 'FATAL',
2022-02-12T11:58:50.712016+00:00 app[web.1]: code: '28000',
2022-02-12T11:58:50.712016+00:00 app[web.1]: detail: undefined,
2022-02-12T11:58:50.712017+00:00 app[web.1]: hint: undefined,
2022-02-12T11:58:50.712017+00:00 app[web.1]: position: undefined,
2022-02-12T11:58:50.712017+00:00 app[web.1]: internalPosition: undefined,
2022-02-12T11:58:50.712018+00:00 app[web.1]: internalQuery: undefined,
2022-02-12T11:58:50.712018+00:00 app[web.1]: where: undefined,
2022-02-12T11:58:50.712018+00:00 app[web.1]: schema: undefined,
2022-02-12T11:58:50.712018+00:00 app[web.1]: table: undefined,
2022-02-12T11:58:50.712019+00:00 app[web.1]: column: undefined,
2022-02-12T11:58:50.712019+00:00 app[web.1]: dataType: undefined,
2022-02-12T11:58:50.712019+00:00 app[web.1]: constraint: undefined,
2022-02-12T11:58:50.712019+00:00 app[web.1]: file: 'auth.c',
2022-02-12T11:58:50.712019+00:00 app[web.1]: line: '496',
2022-02-12T11:58:50.712019+00:00 app[web.1]: routine: 'ClientAuthentication'
2022-02-12T11:58:50.712020+00:00 app[web.1]: }
------------------------------------------------------------------------------------
the app was a nodejs blogging app so there was no need for security
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false,
},
});

Unable to connect to remote MySQL database with mysql package

I have tried to connect to my remote MySQL database server with npm's mysql package but it keeps on throwing this error
But it works fine when I use mysqli with PHP
ERROR:
Error: connect ETIMEDOUT
at PoolConnection.Connection._handleConnectTimeout (/home/rilla/Desktop/dbTest/node_modules/mysql/lib/Connection.js:409:13)
at Object.onceWrapper (events.js:416:28)
at Socket.emit (events.js:310:20)
at Socket._onTimeout (net.js:479:8)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7)
--------------------
at Protocol._enqueue (/home/rilla/Desktop/dbTest/node_modules/mysql/lib/protocol/Protocol.js:144:48)
at Protocol.handshake (/home/rilla/Desktop/dbTest/node_modules/mysql/lib/protocol/Protocol.js:51:23)
at PoolConnection.connect (/home/rilla/Desktop/dbTest/node_modules/mysql/lib/Connection.js:116:18)
at Pool.getConnection (/home/rilla/Desktop/dbTest/node_modules/mysql/lib/Pool.js:48:16)
at Object.<anonymous> (/home/rilla/Desktop/dbTest/test.js:22:6)
at Module._compile (internal/modules/cjs/loader.js:1133:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12) {
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true
}
MY CODE:
// Get the mysql service
var mysql = require("mysql");
// Add the credentials to access your database
// var connection = mysql.createConnection({
// host: "my_host", // hosts IP here
// port: 3306,
// user: "my_username",
// password: "my_password",
// database: "my_database",
// });
var pool = mysql.createPool({
connectionLimit: 100,
host: "my_host", // hosts IP here
port: 3306,
user: "my_username",
password: "my_password",
database: "my_database",
});
pool.getConnection(function (err, conn) {
if (err) {
console.log(err);
} else {
console.log('it works now')
}
});
// connect to mysql
// connection.connect(function (err) {
// // in case of error
// if (err) {
// console.log(err);
// console.log(err.code);
// console.log(err.fatal);
// } else {
// console.log('it works now')
// }
// });
I have tried with sequelize too but no avail. I can't figure why it's not connecting

Heroku Nodejs Reddit bot works fine locally but not online

I have a reddit bot written in Nodejs with Snoowrap and Snoostorm and deployed to Heroku.
My logs keeps churning this error out:
2020-03-13T06:02:53.784219+00:00 app[web.1]: (node:4) UnhandledPromiseRejectionWarning: RequestError: Error: ESOCKETTIMEDOUT
2020-03-13T06:02:53.784229+00:00 app[web.1]: at new RequestError (/app/node_modules/request-promise-core/lib/errors.js:14:15)
2020-03-13T06:02:53.784230+00:00 app[web.1]: at Request.plumbing.callback (/app/node_modules/request-promise-core/lib/plumbing.js:87:29)
2020-03-13T06:02:53.784231+00:00 app[web.1]: at Request.RP$callback [as _callback] (/app/node_modules/request-promise-core/lib/plumbing.js:46:31)
2020-03-13T06:02:53.784231+00:00 app[web.1]: at self.callback (/app/node_modules/request/request.js:185:22)
2020-03-13T06:02:53.784234+00:00 app[web.1]: at Request.emit (events.js:311:20)
2020-03-13T06:02:53.784234+00:00 app[web.1]: at ClientRequest.<anonymous> (/app/node_modules/request/request.js:819:16)
2020-03-13T06:02:53.784235+00:00 app[web.1]: at Object.onceWrapper (events.js:417:28)
2020-03-13T06:02:53.784235+00:00 app[web.1]: at ClientRequest.emit (events.js:311:20)
2020-03-13T06:02:53.784236+00:00 app[web.1]: at TLSSocket.emitRequestTimeout (_http_client.js:714:9)
2020-03-13T06:02:53.784237+00:00 app[web.1]: at Object.onceWrapper (events.js:417:28)
2020-03-13T06:02:53.784237+00:00 app[web.1]: at TLSSocket.emit (events.js:311:20)
2020-03-13T06:02:53.784237+00:00 app[web.1]: at TLSSocket.Socket._onTimeout (net.js:478:8)
2020-03-13T06:02:53.784238+00:00 app[web.1]: at listOnTimeout (internal/timers.js:549:17)
2020-03-13T06:02:53.784238+00:00 app[web.1]: at processTimers (internal/timers.js:492:7)
2020-03-13T06:02:53.784281+00:00 app[web.1]: (node:4) 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)`
Here is my app.js file:
require('dotenv').config();
const MyUtil = require("./myutil.js")
const { CommentStream, SubmissionStream, ModMailStream, InboxStream } = require("snoostorm");
const Snoowrap = require('snoowrap');
const Snoostorm = require('snoostorm');
const WatchJS = require("melanke-watchjs")
const r = new Snoowrap({
userAgent: 'abcde',
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
refreshToken: process.env.REFRESH_TOKEN
});
const BOT_START = Date.now() / 1000;
var webController;
function initializeBot(controller){
configReddit();
watchRateLimit();
initCommentStream();
initPostStream();
initInboxStream();
initModMailStream();
webController = controller;
return module.exports
}
function configReddit(){
r.config({continueAfterRatelimitError: true});
console.info("Finished Reddit configuration.")
}
function watchRateLimit(){
//WATCH JS
// var watch = WatchJS.watch;
// var unwatch = WatchJS.unwatch;
// var callWatchers = WatchJS.callWatchers;
WatchJS.watch(r, "ratelimitRemaining",
() => {
if(r.ratelimitRemaining < 50){
console.warn("Rate limit remaining:" +r.ratelimitRemaining);
}
if(webController){
webController.broadcast(r.ratelimitRemaining);
}
});
}
function initCommentStream(){
console.info("Trying to establish comment stream!");
var streamOpts;
try {
streamOpts = JSON.parse(process.env.COMMENT_STREAM_OPTION);
if(!streamOpts || !streamOpts.receiving){
console.info("Comment Stream was disabled, enable through the environment variable.")
return;
}
} catch (error) {
console.log(error);
console.info("COMMENT_STREAM_OPTION unavailable/wrong format.");
return;
}
const comments = new CommentStream(r, streamOpts);
comments.on("item", comment => {
if(comment.created_utc < BOT_START) return;
if(comment.body.toLowerCase().includes("!resolved")){
console.log("New resolved comment!: "+comment.link_id.substring(3))
let flair = {flair_template_id:MyUtil.FLAIR_ID.RESOLVED}
let sub = r.getSubmission(comment.link_id.toString().substring(3));
let reply = ""; //TODO
sub.selectFlair(flair).then(sub.reply())
}
})
console.info("Comment Stream established.");
}
function initPostStream(){
console.info("Trying to establish post stream!");
var streamOpts
try {
streamOpts = JSON.parse(process.env.POST_STREAM_OPTION);
if(!streamOpts || !streamOpts.receiving){
console.info("Post Stream was disabled, enable through the environment variable.")
return;
}
} catch (error) {
console.log(error)
console.info("POST_STREAM_OPTION unavailable/wrong format.");
return;
}
const posts = new Snoostorm.SubmissionStream(r, streamOpts);
//*Listen for items (posts)
posts.on("item", post =>{
if(post.created_utc < BOT_START) return;
console.log("New POST");
console.log(post.body);
notifyNewPost("/u/abcde", post)
//TODO
})
console.info("Post Stream established!");
}
function initInboxStream(){
//TODO
}
function initModMailStream(){
//TODO
}
async function notifyNewPost(peopleList, post){
if(!post._hasFetched){
try {
post = await post.fetch();
} catch (error) {
console.log("Error at notifyNewPost")
console.log(error);
return
}
}
var sendFunction = function(people, post){
r.composeMessage({
to:people,
subject:"New post in r/GoogleAppsScript",
text:`There's a new post in r/GoogleAppsScript:
[${post.title}](${post.url}) posted by ${post.author.name}
`
}).then(()=>{console.log(`New post notification sent to ${people}.`)})
.catch((err)=>{console.log("Error on sending noti to abcde:\n"+err)});
}
if(typeof peopleList == "string"){
sendFunction(peopleList, post);
}else{
for (const people of peopleList) {
sendFunction(people, post);
}
}
}
module.exports={
initializeBot,
r
}
This is web.js:
const controller = {};
var express = require('express');
var app = express();
const wakeDyno = require("woke-dyno");
const bot = require("./app").initializeBot(controller);
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
app.get('/', function(req, res){
res.sendFile(__dirname + '/html/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(port, ()=>{
wakeDyno("https://gas-lighter-bot.herokuapp.com/").start();
console.log('listening on *:'+port);
});
controller.broadcast = (msg) => {
io.emit("ratelimitChanged",msg);
};
The weird thing is the log don't tell me where the error originated in my code, so I am a bit clueless.
I've been running it for a few hours on my machine, but when deployed to Heroku, it throw this error after like 1 minute....
Please help :(
EDIT: This is the error object, it doesn't help me, but maybe it will help you solve this :(
{
name: 'RequestError',
message: 'Error: ESOCKETTIMEDOUT',
cause: Error: ESOCKETTIMEDOUT
at ClientRequest.<anonymous> (/app/node_modules/request/request.js:816:19)
at Object.onceWrapper (events.js:417:28)
at ClientRequest.emit (events.js:311:20)
at TLSSocket.emitRequestTimeout (_http_client.js:714:9)
at Object.onceWrapper (events.js:417:28)
at TLSSocket.emit (events.js:311:20)
at TLSSocket.Socket._onTimeout (net.js:478:8)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7) {
code: 'ESOCKETTIMEDOUT',
connect: false
},
error: Error: ESOCKETTIMEDOUT
at ClientRequest.<anonymous> (/app/node_modules/request/request.js:816:19)
at Object.onceWrapper (events.js:417:28)
at ClientRequest.emit (events.js:311:20)
at TLSSocket.emitRequestTimeout (_http_client.js:714:9)
at Object.onceWrapper (events.js:417:28)
at TLSSocket.emit (events.js:311:20)
at TLSSocket.Socket._onTimeout (net.js:478:8)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7) {
code: 'ESOCKETTIMEDOUT',
connect: false
},
options: {
gzip: true,
json: true,
headers: { 'user-agent': 'myuseragent' },
baseUrl: 'https://oauth.reddit.com',
qs: { raw_json: 1 },
auth: { bearer: 'myrefreshtoken' },
resolveWithFullResponse: true,
timeout: 5000,
transform: [Function: transform],
uri: 'comments/fhxl4r',
method: 'GET',
callback: [Function: RP$callback],
simple: true,
transform2xxOnly: false
},
response: undefined
}

Categories

Resources