i am currently working on a project where i use nodejs to make a user that adds users to MySql in a table called "users"
i would like to make a button in html which deletes the currently logged in user from the mysql table
how do i make a button in html call a function in nodejs which deletes a Row in MySql
This may be a good start to understand how to trigger API calls from Js
fetch('https://reqres.in/api/deleteUser', {
method: "DELETE",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({
id: '1'
})
})
.then(res => {
if (res.ok) { console.log("HTTP request successful") }
else { console.log("HTTP request unsuccessful") }
return res
})
.then(res => res.json())
.then(data => console.log(data))
.catch(error => console.log(error))
And then for NodeJs
// Module dependencies
var express = require('express'),
ejs = require('ejs'),
fs = require('fs'),
mysql = require('mysql');
// Application initialization
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '' //<your password
});
var app = module.exports = express.createServer();
// Database setup
connection.query('CREATE DATABASE IF NOT EXISTS test', function (err) {
if (err) throw err;
connection.query('USE test', function (err) {
if (err) throw err;
connection.query('CREATE TABLE IF NOT EXISTS users('
+ 'id INT NOT NULL AUTO_INCREMENT,'
+ 'PRIMARY KEY(id),'
+ 'name VARCHAR(30)'
+ ')', function (err) {
if (err) throw err;
});
});
});
// Configuration
app.use(express.bodyParser());
// Post delete user
app.post('/deleteUser', function(req, res) {
var id=Number(req.query.id);
console.log(id);
connection.query('delete from users where id='+id,
});
Related
Is it possible to change the pool config database?
I have a rest API with node/express, and I have multiple databases.
So I need that when a user.company login in my frontend, the API rest, choose the database that user should use.
My configuration file for the bank is this .env
JWT_KEY=XXXXXXX
POOL1_USER=root
POOL1_PASSWORD=xxxxxx
POOL1_DATABASE=data1
POOL1_HOST=host.domain.com
POOL1_PORT=3306
Meu arquivo db.js é este:
const mysql = require("mysql");
const pool1 = mysql.createPool({
connectionLimit: 10,
user: process.env.POOL1_USER,
password: process.env.POOL1_PASSWORD,
database: process.env.POOL1_DATABASE,
host: process.env.POOL1_HOST,
port: process.env.POOL1_PORT,
});
module.exports = { pool1 };
Is this my controllers.js file?
const mysql = require("../db").pool1;
exports.adminGroup = (req, res, next) => {
mysql.getConnection((error, conn) => {
if (error) {
return res.status(500).send({ error: error });
}
conn.query(
"INSERT INTO adminGroup SET ?",
[req.body],
(error, results) => {
conn.release();
if (error) {
return res.status(500).send({ error: error });
}
response = {
mensagem: "Group add",
grupoCriado: {
id: results.insertId,
grupo: req.body.group,
},
};
return res.status(201).send(response);
}
);
});
};
I need to dynamically change the database, as I have the same frontend for the same rest API, but I have multiple databases that can even be on different hosts.
It may be that what I'm trying to implement is not possible, so does anyone have any different suggestions?
Before you use the query to select a table from a database, you need to switch the database, use this query to achieve that.
con.query("USE your_db_name", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
then after it use the query that you want like this
const mysql = require("../db").pool1;
exports.adminGroup = (req, res, next) => {
mysql.getConnection((error, conn) => {
if (error) {
return res.status(500).send({ error: error });
}
con.query("USE your_db_name", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
conn.query(
"INSERT INTO adminGroup SET ?",
[req.body],
(error, results) => {
conn.release();
if (error) {
return res.status(500).send({ error: error });
}
response = {
mensagem: "Group add",
grupoCriado: {
id: results.insertId,
grupo: req.body.group,
},
};
return res.status(201).send(response);
}
);
});
};
i have problem with post method in mysql node js, when i post the request in postman it return an old record i don't know where come from.
in the first i used Get method and it worked very well but when i changed the method to Post i found thid problem.
i use this request for a form in react app i think the problem is not in the form because i tried the request in postman before try it in the app.
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const bodyParser = require('body-parser')
const app = express();
// Connection Mysql
const selectQuery = 'SELECT * FROM userstab';
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'nodeusers',
});
connection.connect(err => {
if (err) {
return err;
}
});
console.log(connection);
// Connection Express Body-Parser Cors
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send('Hello from the products server')
});
app.post('/userss/add', (req, res) => {
const nom = req.body.nom;
const prenom = req.body.prenom;
const adresse = req.body.adresse;
const email = req.body.email;
console.log(nom, prenom);
const insertQuery = `INSERT INTO userstab (nom, prenom, adresse,
email) VALUES
("${nom}","${prenom}","${adresse}",
"${email}")`;
connection.query(insertQuery,[nom,prenom,adresse,email],
(err,results) => {
if(err) {
res.send(err)
}
console.log(nom, prenom);
res.send({ error: false, data: results, message: 'user has
been added successfully.' });
})
});
// First Get request/////////////////////////////////////////
app.get('/userss/add', (req, res) => {
const { nom, prenom, adresse, email } = req.query;
const insertQuery = `INSERT INTO userstab (nom, prenom, adresse, email) VALUES ('${nom}','${prenom}','${adresse}','${email}')`;
connection.query(insertQuery, (err, results) => {
if(err) {
return res.send(err)
}
else {
return res.send('successfully added user')
}
});
});
////////////////////////////////////////////////////////////////////
app.listen(4000, () => {
console.log('Users server worked on port 4000...')
});
Because you are using users table in post request , and another table called userstab in get request.
So please change you query in post request to be the same table in get request.
Need your help. I am trying to implement global request id for my nodejs application. For that I am using express-http-context lib to set request id. But it's not working as expected when my code access data from mysql database. Seems like there is a compatibility issue in cls used by express-http-context and mysql library.
Sample code and the output is provided below:
const app = require('express')();
const httpContext = require('express-http-context');
const mysql = require('mysql');
const { INTERNAL_SERVER_ERROR, OK, NOT_FOUND } = require('http-status-codes');
const http = require('http');
const uuidv4 = require('uuid/v4');
const pool = mysql.createPool({
host: '127.0.0.1',
port: 3306,
user: 'root',
password: 'Redhat#123',
database: 'user',
connectionLimit: 10,
});
pool.query('SELECT 1 + 1 AS solution', (error) => {
if (error) {
console.log('Unable to connect to MySQL:- ', error.message);
process.exit(1);
}
console.log('MySQL PING is Working');
});
app.use(httpContext.middleware);
app.use((req, res, next) => {
httpContext.set('requestId', uuidv4());
console.log('request Id set is: ', httpContext.get('requestId'));
next();
});
const getUserDetailsRepository = (userId, callback) => {
console.log('inside getuserDetails repository for request id: ', httpContext.get('requestId'));
pool.getConnection((connectionError, connection) => {
if (connectionError) {
console.log('got ConnError getuserDetails repository for request id: ', httpContext.get('requestId'));
callback(connectionError);
} else {
const query = 'SELECT * from user where id = ?';
connection.query(query, [userId], (queryError, results) => {
connection.release();
if (queryError) {
console.log('got queryError getuserDetails repository for request id: ', httpContext.get('requestId'), queryError.message);
callback(queryError);
} else {
console.log('Got response inside getuserDetails repository for request id: ', httpContext.get('requestId'));
callback(null, results);
}
});
}
});
};
const userGetDetails = (req, res, next) => {
const { userId } = req.params;
console.log('inside getUserDetails controller for request id: ', httpContext.get('requestId'));
getUserDetailsRepository(userId, (error, result) => {
if (error) {
console.log('got Error in getuserDetails controller for request id: ', httpContext.get('requestId'))
res.sendStatus(INTERNAL_SERVER_ERROR);
} else if (result) {
console.log('Got response inside getuserDetails repository for request id: ', httpContext.get('requestId'));
res.status(OK).json(result);
} else {
res.sendStatus(NOT_FOUND);
}
});
};
app.get('/user/:userId', userGetDetails);
const server = http.createServer(app);
server.listen(3000, () => console.log('Http server started listening on port'));
Output:
Http server started listening on port
MySQL PING is Working
request Id set is: ea4895ab-8003-4d28-99aa-b03af7027ae8
inside getUserDetails controller for request id: ea4895ab-8003-4d28-99aa-b03af7027ae8
inside getuserDetails repository for request id: ea4895ab-8003-4d28-99aa-b03af7027ae8
Got response inside getuserDetails repository for request id: undefined
Got response inside getuserDetails repository for request id: undefined
i hope this solution solve your problem and save many hours for anyone that have this problem
you can just use bindEmitter to solve the problem
app.use((req, res, next) => {
httpContext.ns.bindEmitter(req);
httpContext.ns.bindEmitter(res);
var requestId = req.headers["x-request-id"] || uuidv4();
httpContext.set("requestId", requestId);
console.log('request Id set is: ', httpContext.get('requestId'));
next();
});
I'm using elasticsearch, node, and MySql. I need to sync some user data from MySql to elasticsearch. My route is set up like:
router.post("/register_user", (req, res, next) => {
mysql.register(req.body).then((result) => {
elastic.createUser(...);
});
});
When a user posts to this route, it successfully creates a row in mysql:
const mysql = require("mysql");
const connection = mysql.createConnection("...");
connection.connect();
exports.register = (req, res) => {
const user = { name: req.name };
connection.query('INSERT INTO user SET ?', user, (err, rows) => {
// stuff for errors
// ...
connection.end();
// what do I do here?
});
});
I tried:
// I got an error regarding "status of undefined"
res.status(200).json({ id: rows.insertId });
// I got something about "then of undefined" in the router
return { id: rows.insertId };
How to handle Delete Query When id not available in App.delete method not giving error .in both case show success. if id not available then it should output id not available to delete task .
same case for get by id method . if id is available it working right . if id not available it did not show error
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mysql = require('mysql');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// connection configurations
const mc = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: '1234'
});
// connect to database
mc.connect();
// default route
app.get('/', function (req, res) {
return res.send({ error: true, message: 'hello' })
});
// Retrieve all todos
app.get('/todos', function (req, res) {
mc.query('SELECT * FROM tasks', function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'Todos list.' });
});
});
// Search for todos with ‘bug’ in their name
app.get('/todos/search/:keyword', function (req, res) {
let keyword = req.params.keyword;
mc.query("SELECT * FROM tasks WHERE task LIKE ? ", ['%' + keyword + '%'], function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'Todos search list.' });
});
});
// Retrieve todo with id
app.get('/todo/:id', function (req, res) {
let task_id = req.params.id;
mc.query('SELECT * FROM tasks where id=?', task_id, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results[0], message: 'Todos list.' });
});
});
// Add a new todo
app.post('/todo', function (req, res) {
let task = req.body.task;
if (!task) {
return res.status(400).send({ error:true, message: 'Please provide task' });
}
mc.query("INSERT INTO tasks SET ? ", { task: task }, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'New task has been created successfully.' });
});
});
// Update todo with id
app.put('/todo', function (req, res) {
let task_id = req.body.task_id;
let task = req.body.task;
if (!task_id || !task) {
return res.status(400).send({ error: task, message: 'Please provide task and task_id' });
}
mc.query("UPDATE tasks SET task = ? WHERE id = ?", [task, task_id], function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'Task has been updated successfully.' });
});
});
// Delete todo
app.delete('/todo/:id', function (req, res) {
let task_id = req.params.id;
if (!task_id) {
return res.status(400).send({ error: true, message: 'Please provide text_id' });
}
mc.query('DELETE FROM tasks WHERE id = ?', task_id, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'text has been Deleted successfully.' });
});
});
// all other requests redirect to 404
app.all("*", function (req, res) {
return res.status(404).send('page not found')
});
// port must be set to 8080 because incoming http requests are routed from port 80 to port 8080
app.listen(8080, function () {
console.log('Node app is running on port 8080');
});
// allows "grunt dev" to create a development server with livereload
//module.exports = app;
You have to define the param as optional.
Express uses path-to-regexp for matching the route paths; see the
path-to-regexp documentation for all the possibilities in defining
route paths. Express Route Tester is a handy tool for testing basic
Express routes, although it does not support pattern matching.
https://expressjs.com/en/guide/routing.html
Works for /todo and /todo/{id},
route - /todo/:id*?
// Delete todo
app.delete('/todo/:id*?', function (req, res) {
});