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

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();
}
});

Related

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"

How to query a mysql database with Node.js to get specific users (fields) by name in url, not only by ID

I know how to query a SQLite Database with Node.js to bring back a specific key with the corresponding field information but I am unable to find the right syntax to do it in Mysql.
I want to put a specific station name in the url such as and result all its information from the database. example. http://localhost:5000/station/
The database result would be:
["station":"winton", "location":"123 Byers Lane", "property size":"3000"]
<sqlite> needs to be put in <mysql>
app.get('station/:stationid', req, res) => {
const stationToLookup = req.params.stationid;
db.all (
'SELECT * FROM stores WHERE station = $station',
{
$station = stationToLookup
},
(err, rows) => {
console.log(rows);
if (rows.length > 0){
res.send (rows[0]);
}else{
res.send({});
}
});
});
You should install mysql driver first via npm. npm install mysql
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
app.get('station/:stationid', req, res) => {
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM stores WHERE station ='" + req.params.stationid + "'", function (err, result) {
if (err) throw err;
console.log(result);
});
});
}
NOTE how the double quotes and single quotes have been used in the code above. The query is inside double quotes and then the value of a field which we are going to find is between single qoutes embedded inside double qoutes just after the = sign.
Here seems to be a solutioin.....#James #SonuBamniya
//(2)getting all stations names
app.get('/stationNames/:stationid',(req,res)=>{
const nameToLookup = req.params.stationid;
//console.log(nameToLookup);
db.query('SELECT * FROM stores WHERE station = ?', [nameToLookup],(err, rows, fields)=>{
if(!err)
res.send(rows);
else
console.log(err);
})
});

Post isn't sending data do mySql table

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.

Nodejs querying single data instead of all from mongodb collection

I am trying to fetch data from mongodb's collection. My code is executing only single row data in json format. But when I console log my data I can see all the row data.
const mongoose = require('mongoose');
const AllMinisters = require('../models/allMinisters');
var db;
var mongodb = require("mongodb");
// Initialize connection once
mongoose.connect("******", { useNewUrlParser: true }, function(err, database) {
if(err) return console.error(err);
db = database;
// the Mongo driver recommends starting the server here because most apps *should* fail to start if they have no DB. If yours is the exception, move the server startup elsewhere.
});
exports.getAllMinisters = (req,res,next)=>{
db.collection("users").find({}, function(err, docs) {
if(err) return next(err);
docs.each(function(err, doc) {
if(doc) {
console.log(doc);
var response = {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: doc
}
res.end(JSON.stringify(response));
}
});
});
};
This output in JSON as
However the console report shows all
How can I show all row data in JSON
You have docs.each in your code that will iterate over all the doc you get from the find() query (which is an array) and inside that each block you are sending the response i.e, res.end(JSON.stringify(response));, which executes immediately for the first record and hence you get a single object as a response instead of array.
To return the array you need to put res.end(JSON.stringify(response)); outside the each() loop with toArray function. You can even remove the each() loop if that is not required. So, your code will be something like:
exports.getAllMinisters = (req, res, next)=>{
db.collection('users').find({}).toArray(function (err, docs) {
if (err) {return next(err);}
docs.each(function (err, doc) {
if (doc) {
//code for single doc
console.log(doc);
}
});
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(docs));
});
};

Passing Object with module exports

I am still new to nodejs and Javascript, I am sorry if my question appear to be very simple but I am struggling a lot and I can't seem to find an answer on the net.
What I want to do is basically calling a script (sqlRequest.js) and send an integer while calling it. This script will send an sql request to my database and will return the result (an object) to the original file.
Here are the codes:
router.post('/request', function(req, res, next){
var id = req.body.id;
var essai = require('./sqlRequest.js');
console.log("INDEX: "+essai.sendSQL(id)); });
And now the sqlRequest.js code:
exports.sendSQL = function(id) {
var mysql= require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'bcombes',
password : 'bertrand1994',
database : 'totalkpi'
});
connection.connect();
var sql ="SELECT * FROM tra_ticket where id=?";
var insert=[id];
sql=mysql.format(sql, insert);
connection.query(sql, function(err, rows, fields) {
if (err) {
console.log('Error while performing Query.');
connection.end();
}
else {
connection.end();
console.log(rows);
return rows;
}
});};
On the console I can see that the console.log("INDEX: "+essai.sendSQL(id)); appears to be undefined and is displayed before the console.log(rows).
Is it possible that the server does not wait for the function to finish and display the variable anyway ?
Anyway thank you for taking the time to help.
Your logic to pass a variable between files is fine. The reason your seeing essai.sendSQL(id) return undefined is because connection.query(...) is called asynchronously and, as you've mentioned in your question, the console.log fires before the DB query completes.
To fix that issue you just need to refactor your code slightly:
var essai = require('./sqlRequest.js');
router.post('/request', function(req, res, next){
var id = req.body.id;
// send callback to sendSQL
essai.sendSQL(id, function(index) {
// this will only fire once the callback has been called
console.log("INDEX: " + index)
})
});
And then in sqlRequest.js:
exports.sendSQL = function (id, cb) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'bcombes',
password: 'bertrand1994',
database: 'totalkpi'
});
connection.connect();
var sql = "SELECT * FROM tra_ticket where id=?";
var insert = [id];
sql = mysql.format(sql, insert);
connection.query(sql, function (err, rows, fields) {
if (err) {
console.log('Error while performing Query.');
connection.end();
}
else {
connection.end();
console.log(rows);
// call the callback
cb(rows);
}
});
};

Categories

Resources