Post isn't sending data do mySql table - javascript

I'm new at programming and I've been trying to make a post that allows me to send data from an ancount form into a table( mysql database). However the console.log(on the node node console shows me an error) and I can't seem to understand why the post isn't working.
I get the error cannot enqueue Handshake after already enqueuing a Handshake, even though I've googled about, I haven't found a way to make the post work or get rid of this error.
Appreciate for any help.
const express = require('express');
const mysql = require('mysql');
// Create connection
const db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'nodemysql'
});
// Connect
db.connect((err) => {
if(err){
throw err;
}
console.log('MySql Connected...');
});
const app = express();
app.get('/', function (req, res) {//nome da minha url req(é o que vai na url/ res é o response é o ficheiro)
res.sendFile(path.join(__dirname+'/public/index.html'));
})
app.get('/log_in', function (req, res) {//nome da minha url
res.sendFile(path.join(__dirname+'/public/signin.html'));
})
app.get('/register', function (req, res) {//nome da minha url
res.sendFile(path.join(__dirname+'/public/register.html'));
})
// Create DB
app.get('/createdb', (req, res) => {
let sql = 'CREATE DATABASE IF NOT EXISTS nodemysql';
db.query(sql, (err, result) => {
if(err) throw err;
console.log(result);
res.send('Database created...');
});
});
// Create table
app.get('/createusertable', (req, res) => {
let sql = 'CREATE TABLE user (id int AUTO_INCREMENT, name VARCHAR(50), last_name VARCHAR(50),email VARCHAR(100),password VARCHAR (100),phone VARCHAR (50),country VARCHAR(100),vat_number VARCHAR(9),address VARCHAR(150), PRIMARY KEY(id))';
db.query(sql, (err, result) => {
if(err) throw err;
console.log(result);
res.send('Post table created...');
});
});
db.connect(function(err){
if(err) return console.log(err);
console.log('conectou!');
createTable(connection);
})
app.listen('3000', () => {
console.log('Server started on port 3000');
});
app.use(express.static('public'))
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.post('/register', function (req, res) {
console.log(req.body.user.name);
let post = {name:req.body.user.name, last_name:req.body.user.lastName,
email:req.body.user.email, password:req.body.user.password, phone:req.body.user.phone,
country:req.body.user.country, vat_number:req.body.user.nif, address:req.body.user.address};
let sql = 'INSERT INTO user SET ?';
let query = db.query(sql, post, (err, result) => {
if(err) throw err;
res.redirect(303,'/');
});
});

It looks like you initiate another db.connect in your create table step after you already initiated a connect in the beginning of your script.
This is a double connection initiation, without any connection.end(); to close the initially opened connection.
I think you will have more luck when you remove the db.connect from your "create table" step.
Please view this documentation to further clarify my point.

Related

Getting Username with node.js and redirecting (success/failure)

i am getting started with node.js and now I got stuck.
var mysql = require('mysql');
var dbconfig = require('../config/database');
var connection = mysql.createConnection(dbconfig.connection);
connection.query('USE ' + dbconfig.database);
app.get('/createarticle', isLoggedIn, function(req, res){
res.render('createarticle.ejs', {
user:req.user
});
});
app.post('/createarticle' , (req, res ) => {
let sql = 'INSERT INTO news SET ?'
let post = {
// author: req.user.username,
content : req.body.content,
title: req.body.title
}
connection.query(sql, post, (err, res) => {
if(err) throw err;
console.log('success');
console.log(res);
});
});
If I use req.user.username I get this error message Cannot read property 'username' of undefined.
I also tried user.username and req.user.
In my main JS I have this function that shoud always give the user if logged in.
app.get('*', function(req, res, next) {
res.locals.user = req.user || null;
next();
});
In addition to this I want to include two redirects but I don't know where to put it.
successRedirect: '/',
failureRedirect: '/createarticle',
I appreciate every answer and pacience with me. :)
I can't comment so I have to post an answer:
What does your request object look like:
app.get('/createarticle', isLoggedIn, function(req, res){
console.log('request',req)
res.render('createarticle.ejs', {
user:req.user
});
});
If you're not populating the request object in your 'GET' from your front end,
you won't have the user you are asking for.
You may want to do some handling in the front to make sure that you only send populated request objects.

Records missing after insert into table via http request mysql

I am attempting to insert data into a database on aws, a mysql db. I am able to send the data to the endpoint, it shows up for a bit but then dissapears. I am sending it via react. Below is the code I am using:
addRecord =() => {
fetch(`my_ip:4000/data/add?time=${moment().format("YYYY-MM-DD HH:mm:00")}&lat=${this.state.lat}&lon=${this.state.lon}&floor=${this.state.floor}`)
.catch(err => console.error(err))
}
API endpoint is in Node below:
//add a record
app.get('/data/add', (req, res) => {
const { time, lat, lon, floor } = req.query;
const INSERT_RECORDS = `INSERT INTO table_x(time, lat, lon, floor) VALUES('${time}','${lat}','${lon}',${floor})`;
connection.query(INSERT_RECORDS, (err, results) => {
if(err) {
return res.send(err)
} else {
return res.send('successfully added')
}
});
});
The records appear in the table for about 5 seconds and then disappear. I believe something is going on with "commiting" in sql but not aware how to fix this.
Attempt
I've tried to switch to post as I have seen this in some other posts like:
Adding data to mysql database with node.js
But still not working. If I use app.get() it works but again the data does not persist. it appears in my database for approximately ten seconds, then it simply disappears as if deleted:
const SELECT_ALL_PRODUCTS_QUERY = 'SELECT * FROM my_table';
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const app = express();
connection.connect(err => {
if(err) {
return err;
} else {
console.log('success')
}
});
app.use(cors());
//create api directions
app.get('/', (req, res) => {
res.send('go to /products to see products')
});
app.listen(4000, () => {
console.log('Server listening on port 4000')
});
//call query to select all
app.get('/products', (req, res) => {
connection.query(SELECT_ALL_PRODUCTS_QUERY, (err, results) => {
if(err) {
return res.send(err)
} else {
console.log(results)
return res.json({
data: results
})
}
})
})
app.post('/add', (req, res) => {
console.log(req.query);
var my_data = {
time: req.query.time,
lat: req.query.lat,
lon: req.query.lon,
floor: req.query.floor
}
// now the createStudent is an object you can use in your database insert logic.
connection.query('INSERT INTO my_table SET ?', my_data, function (err, resp) {
if (err) throw err;
// if there are no errors send an OK message.
res.send('Saved successfully');
});
});
When I attempt to add a record via:
http://my_ip:4000/add?time=2019-10-01%2009:00:00&lat=43.07&lon=-73.08&floor=1
I get the error:
CANNOT GET /add
Once again, if I use app.get() it works but does not persist
When I insert data via the addRecord function I see the following console log on my backend terminal:
Server listening on port 4000
success
{ time: '2019-11-24 17:16:00',
lat: '43',
lon: '-73.1',
floor: '0' }
So it seems the data is received. But I don't see "saved successfully"

Data deletion from database dynamically using delete request in node.js

I am using normal http request for deleting value from mysql database using node.js. But right now, only values are deleted statically not dynamically. I want to delete the data dynamically by providing the id.
const server = http.createServer();
const reqUrl = url.parse(req.url, true);
server.on('request', (req, res) => {
if (reqUrl.pathname === '/delete'){
req.on('end', () => {
let sql = "Delete from students where id=12";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
})
res.end();
}
});
now, after running this code localhost:3000/delete only the id=12 is deleted all time. But I want to do this localhost:3000/delete?id=12 giving input values as id.
I tried to give sql command as "Delete from students where id=?" , but it gave errors. How can I solve this?
That should be simple.
You just need to receive the param from your request and append it to string.
Here's your updated code.
server.on('request', (req, res) => {
if (reqUrl.pathname === '/delete'){
req.on('end', () => {
let studid = req.query.id; //Get the student id
let sql = "Delete from students where id="+studid; //append it to query
connection.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
})
res.end();
}
});

Cannot get any response from api created with Express.js and SQL Server

i'm trying to learn how to build an api with Node and Express.js. I've found the next step by step: click here
And created a very similar version but with my data:
var express = require("express");
var bodyParser = require("body-parser");
var sql = require("mssql");
var app = express();
app.use(bodyParser.json());
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, contentType,Content-Type, Accept, Authorization");
next();
});
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
var dbConfig = {
user: "myUser",
password: "myPass",
server: "myServer",
database: "MyDB"
};
var executeQuery = function(res, query){
sql.connect(dbConfig, function (err) {
if (err) {
console.log("Error al conectarse a la base :- " + err);
res.send(err);
}
else {
// create Request object
var request = new sql.Request();
// query to the database
request.query(query, function (err, res) {
if (err) {
console.log("Error al correr query en la base :- " + err);
res.send(err);
}
else {
res.send(res);
}
});
}
});
}
//GET API
app.get("/api/ApiRequestData", function(req, res){
var query = "select * from [RequestData]";
executeQuery (res, query);
});
After create the server.js doc, executed with npm install and run with node server.js, i opened on postman using the next url: http://localhost:8080/api/ApiRequestData and get an error message: "Could not get any response". On the Node command prompt i get the message:
TypeError: res.send is not a function
at C:\Users\API\server.js:43:44
at C:\Users\API\node_modules\mssql\lib\main.js:1588:20
at Request.userCallback (C:\Users\API\node_modules\mssql\lib\tedious.js:853:61)
at Request.callback (C:\Users\API\node_modules\tedious\lib\request.js:33:27)
at Connection.message (C:\Users\API\node_modules\tedious\lib\connection.js:1179:27)
at Connection.dispatchEvent (C:\Users\API\node_modules\tedious\lib\connection.js:519:45)
at MessageIO. (C:\Users\API\node_modules\tedious\lib\connection.js:439:23)
at emitNone (events.js:106:13)
at MessageIO.emit (events.js:208:7)
at ReadablePacketStream. (C:\Users\API\node_modules\tedious\lib\message-io.js:92:15)
Someone knows why shows this message?
Hope you can help me.
You are shadowing res from line var executeQuery = function(res, query){... with res from line request.query(query, function (err, res) {.... Just rename the last res to something else and you won't get this error:
request.query(query, function (err, result) {
if (err) {
console.log("Error al correr query en la base :- " + err);
res.send(err);
}
else {
res.send(result);
}
});
You can use below query for fetching the records with hard coded query like.
I used same for my application.
sql.connect(config).then(() => {
return sql.query`select * from [dbo].[Customer]`
}).then(result => {
console.log(result)
}).catch(err => {
console.log(err);
})
Fetch the result using store procedure.
sql.connect(config).then(pool => {
return pool.request().input('Customerid', sql.Int, 2).execute("GetCustomerbyId")
}).then(result => {
console.log(result)
}).catch(err => {
console.log(err);
})

Mysql node.js intermittent connectivity issue

In my node.js app I am using the mysql library for database connectivity.
When I start my node server I can query the database perfectly fine – no issues
When I query the database after 5 minutes the server returns the following error:
{"code":"PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR","fatal":false}
If I restart my node.js server I can query again with no issues…
Here is my code
const mysql = require('mysql');
let connection = mysql.createPool({
host: config.mysql.host,
user: config.mysql.user,
password: config.mysql.password,
database: config.mysql.database
});
router.post('/subscription', (req, res) => {
const user = req.body;
const q = 'INSERT into Subscription SET ?';
connection.query(q, user, (err, results) => {
if (err)
return res.json(err);
return res.json(results);
});
});
I have used both mysql.createConnection and mysql.createPool…. also tried ending the connection manually with connection.end….
Both results end in the same error.
You need to get a connection from the pool and use that, not query the pool itself. When you get a connection from the pool, the pool will make sure you get a valid connection from the pool. So your code would be:
const mysql = require('mysql');
let pool = mysql.createPool({
host: config.mysql.host,
user: config.mysql.user,
password: config.mysql.password,
database: config.mysql.database
});
router.post('/subscription', (req, res) => {
const user = req.body;
const q = 'INSERT into Subscription SET ?';
pool.getConnection(function(err, connection) {
if (err)
return res.json(err);
connection.query(q, user, (err, results) => {
if (err)
return res.json(err);
return res.json(results);
});
})
});
UPDATE:
You don't need to do separate pool.getConnection and connection.query, you can combine them into a pool.query which will get a connection, do the query and release the connection. So, the updated code would be:
const mysql = require('mysql');
let pool = mysql.createPool({
host: config.mysql.host,
user: config.mysql.user,
password: config.mysql.password,
database: config.mysql.database
});
router.post('/subscription', (req, res) => {
const user = req.body;
const q = 'INSERT into Subscription SET ?';
pool.query(q, user, function(err, connection) {
if (err)
return res.json(err);
return res.json(results);
});
});

Categories

Resources