Why is this POST request failing from Postman? - mysql

Backend of my app is deployed on Heroku using Cleardb addon.
Below is the Backend code: For what I can tell it is hitting the POST requst.
const express = require('express');
const cors = require('cors');
//const mysql = require("mysql");
//this was the old way and did not support secure password
mysql = require('mysql2');
const app = express();
const port = process.env.PORT || 8000
/*
local connection
const db = mysql.createConnection({
connectionaLimit: 50,
user:'root',
host: 'localhost',
password:'',
database:'sys',
port: 3306
});
*/
const db = mysql.createConnection({
connectionaLimit: 120,
user: process.env.DB_USER,
host: process.env.DB_HOST,
password: process.env.DB_PASSWORD,
database: process.env.DATABASE,
port: 3306
});
app.use(cors());
app.use(express.urlencoded({extended: true}));
app.use(express.json());
//SQL connection test
db.connect((err) => {
if (err) console.error(err);
console.log('MySQL Connection Established.');
});
/* not used get request
app.get('/', (req,res) => {
res.header("Access-Control-Allow-Origin", "*");
res.send('Hello back');
}
);
*/
app.post('/' , (req,res) => {
const {email, name, question} = req.body;
res.header("Access-Control-Allow-Origin", "*");
console.log(`Your Email is ${email} and your name is ${name} and your ${question}`);
//MYSQL updating table
db.query("INSERT INTO customer_questions (name, email, question) VALUES (?,?,?)",
[name, email, question], (err,result)=> {
if (err) {
console.log(err)
}else {
res.send('data sent')
}
db.end();
}
);
});
app.listen(port);
console.log(`server is listing on ${port}`);
This is the error log. From what I can tell it the server runs and then stops and the post request hits status 500. I can tell why this is happening.
Post request using POSTMAN showing body.
Any help on this would be helpful. The MYSQL connection works both locally and through Heroku.

Use a connection pool and don't close the connection:
db.end();
You can run querys on the pool object and it will take care of opening/closing connections for you.

Related

Getting PROTOCOL_PACKETS_OUT_OF_ORDER in MySQL Node.js connection

I am an absolute newbie to Node.js. I am trying to create a MySQL database and connect it to a node.js server and build APIs.
Here's my db.config.js:
const mysql = require('mysql');
//local mysql db connection
const dbConn = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'node_mysql_crud_db'
});
dbConn.connect(function(err) {
if (err) throw err;
console.log("Database Connected!");
});
module.exports = dbConn;
And here's my server.js:
const express = require('express');
const bodyParser = require('body-parser');
// create express app
const app = express();
// Setup server port
const port = process.env.PORT || 3306;
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }))
// parse requests of content-type - application/json
app.use(bodyParser.json())
// define a root route
app.get('/', (req, res) => {
res.send("Hello World");
});
// Require employee routes
const employeeRoutes = require('./src/routes/employee.routes')
// using as middleware
app.use('/api/v1/employees', employeeRoutes)
// listen for requests
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
When I run nodemon server, I get the following error:
/Users/mac/Flutter_Projects/NodeMysqlCrudApp/config/db.config.js:12
if (err) throw err;
^
Error: Packets out of order. Got: 80 Expected: 0
code: 'PROTOCOL_PACKETS_OUT_OF_ORDER',
fatal: true
I have added max_allowed_packet=500M in my.cnf file and yet I continue to receive the error.
How to resolve this issue?

Getting "Cannot GET /isFavorite" on my Node.js app hosted on DigitalOcean

Why am I getting the following error? I have a small Nodejs app hosted on DigitalOcean. I am getting the following error "Cannot GET /isFavorite" when I run the following post command in Postman: "http://octopus-app-s7q5v.ondigitalocean.app:8080/isFavorite" with body JSON parameters of:
{
"userid": "101",
"petid": "1"
}
The route I have for the app is an app.post("/isFavorite") and not an app.get. It is connected to a MySQL database which is also hosted on DigitalOcean. I have included a small version of the code for the app below. Why would I be getting this error? When I add an app.get("/") and return a response of "Hello" that works. It runs locally. I have configured all the environment variables in DigitalOcean settings. I have the "ca-certificate.crt" in the root of my Nodejs app. DigitalOcean app platform says it builds and deploys fine on the server.
Also, regarding the console.logs I have added to the code, where are they stored? I can see the one which starts the webserver and listens but not any of the others. The app is listening on port 8080 and has an IP address of 0.0.0.0.
const bodyParser = require("body-parser");
const querystring = require('querystring');
const router = express.Router();
const app = express();
app.use("/", router);
const mysql = require('mysql');
const fs = require('fs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.json());
app.post("/isFavorite", (req, res) => {
try {
console.debug("isFavorite Start");
const conn = mysql.createConnection({
host: process.env.DBHOST,
port: process.env.DBPORT,
user: process.env.DBUSER,
database: process.env.DBNAME,
password: process.env.DBPASSWORD
});
console.log("isFavorite logged on to db");
let selectQuery = 'SELECT COUNT(*) c FROM Favorites WHERE userID = ? AND petID = ?';
let query = mysql.format(selectQuery,[req.body.userid, req.body.petid]);
conn.query(query,(err, response, fields) => {
if(err) {
console.log(err);
res.status(500).send("Error querying database.");
return;
}
// rows added
console.log("isFavorite");
console.log(response.length);
if (response.length > 0) {
console.log(JSON.stringify(response));
res.status(200).json({IsFavorite: response[0].c >= 1});
} else {
res.status(200).json({IsFavorite: false});
}
});
} catch (err) {
next(err);
}
});
let PORT = process.env.PORT || 3000;
let IP = process.env.IP || '127.0.0.1';
app.listen(PORT, IP, () => {
console.log('Server is running at port ' + PORT + ' and IP = ' + IP);
});

How do I resolve this error of postman which is unable to send request?

Hii I am connecting Mysql Workbench and Nodejs to which the connection is successful. After the connection I have made a single get request which to me seems correct but I am still getting an error in the Postman! Can anyone help me?Here is my code-
const express = require('express')
const app = express();
var mysql = require('mysql')
var bodyParser = require('body-parser')
// db connection ----
var con = mysql.createConnection({
host:'localhost',
user:'root',
database:'tutorial',
password:'root'
})
con.connect(function(err){
if(err){
console.log("Error connecting to db");
}
else{
console.log("Connection established ");
}
})
const port = 8080;
app.listen(()=>{
console.log("Server started at port",port)
})
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.get('/customer/' , (req, res) => {
con.query('SELECT * FROM customer', (err, rows, fields) => {
if (!err)
res.send(rows);
else
console.log(err);
})
} );
module.exports = { app }
And this is the error I am getting in postman-
This is the console for vs code-
This is the console of postman-
You did not set the port in listen
app.listen(port, ()=>{
console.log("Server started at port",port)
})
Have you explicitly set the port to 8080 somewhere else? Express generator creates a www file in the bin folder, where your can set the port.
var port = normalizePort(process.env.PORT || '8080');
app.set('port', port);
You can also set the port in listen
app.listen(port, () => {
console.log("Server started at port", port);
});

Express taking forever to load mySQL query?

I'm trying to query a single line from a 28k record database as a test but it isn't going through but when I load up 'localhost:3001/api/get' it stays loading, even though my connection says success? Is it actually even connecting to the db?
my data bases schema is:
id | state_name | city
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const mysql = require('mysql');
const cors = require('cors');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "password",
database: "states_city"
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended:true}));
app.get('/api/get', (req, res)=>{
const sqlGet = "SELECT city FROM state_city city = 'Chicago'";
db.query(sqlGet, (err, res)=>{
console.log("success");
});
});
app.listen(3001, ()=>{
console.log("running on port 3001");
});
First you must make server running. Remove that API route you had set before running server.
app.listen(3001, ()=>{
console.log("running on port 3001");
});
Now you must create database connection. Create new file dbconn.js
var mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "password",
database: "states_city"
});
Now create new connection:
var new_connection = mysql.createPool(
db
);
new_connection.on('connection', function (connection) {
console.log('DB Connection established');
connection.on('error', function (err) {
console.error(new Date(), 'MySQL error', err.code);
});
connection.on('close', function (err) {
console.error(new Date(), 'MySQL close', err);
});
});
// export connection
module.exports = new_connection;
Include that connection in other file:
var db_connection = require('../dbconn');
db_connection.query(query, params, function (error, results, fields) {
//Do your query
});
Read about project structure to make your code easy to edit.

Cannot connect to SQL DB with Nodejs

I'm trying to connect to remote SQL server. I do connect from SQL Management Studio without problems, but with the code below i wait like 2-3 mins to get error ECONNRESET, what's wrong? Why do I wait so much?
let mysql = require('mysql'),
express = require('express'),
bodyParser = require('body-parser'),
app = new express(),
_port = process.env.port || 3000;
let con = mysql.createConnection({
host: '***.***.***.***',
port: ****,
user: "*****",
password: "****"
});
con.connect( function (err) {
if (err) console.log(err);
console.log('connected');
})
app.get('/', (req, res) => {
res.send('ffs');
});
app.listen(_port, () => {
console.log('listening on port ' + _port);
});
The mysql version is 2.11.0 atm, but i tried with the latest one first.