How to pass id in where clause using node.js and MySQL?
Viewer.jsx
async function redeem(cid) {
fetch('http://localhost:4000/getDetailsFromCid/${cid}').then(response => {
return response.json()
})
.then(posts => {
console.log("posts", posts)
})
.then((err) => {
console.log(err);
})
}
index.js
app.get("/api/getDetailsFromCid/:cid", (req, res) => {
const cid = req.params.cid;
db.query("SELECT * FROM Details WHERE cid = ?", [cid],
(err, result) => {
if (err) {
console.log(err)
}
res.send(result)
});
});
Error
Viewer.jsx:19 GET http://localhost:4000/getDetailsFromCid/$%7Bcid%7D 404 (Not Found)
you need to use `` not ''
fetch(`http://localhost:4000/getDetailsFromCid/${cid}`)
Related
I have a question how do I post two similar columns, I tried sending it with array using for of cause I'm using async/await and when I only post one column it works perfectly, but it doesn't when it has two similar columns, any information would really help me
here are my models
postItems: function (setData) {
return new Promise((resolve, reject) => {
db.query('INSERT INTO datas (picture, name, price, quantity, delivery_on, data_description) VALUES (?, ?, ?, ?, ?, ?)', [setData.picture, setData.name, setData.price, setData.quantity, setData.delivery_on, setData.data_description], function (err, res) {
if (!err) {
resolve(res)
} else {
reject(err)
}
})
})
}
postItemsToItemCategory: function (setData) {
return new Promise((resolve, reject) => {
db.query('INSERT INTO data_categories ( data_id, category_id) VALUES (?, ?)', [setData.data_id, setData.category_id], function (err, res) {
if (!err) {
resolve(res)
} else {
reject(err)
}
})
})
}
and here's my controller
postItemData: async function (req, res) {
const setData = req.body
try {
if (setData.price < 1) {
return helper.response(res, 'fail', 'Cannot type number below 1', 400)
}
const result = await itemModels.postItems(setData)
const categoryData = {
data_id: result.insertId,
category_id: setData.category_id
}
if (typeof categoryData.category_id !== 'object') {
categoryData.category_id = [categoryData.category_id]
}
for (const category of [categoryData]) {
try {
console.log(categoryData)
await postItemsToItemCategory(category)
console.log(`product ${result.insertId} has been created on category ${setData.category_id}!`)
} catch (err) {
console.log(err)
}
}
return helper.response(res, 'success', result, 200)
} catch (err) {
console.log(err)
return helper.response(res, 'fail', 'Internal Server Error!', 500)
}
}
I fixed my code, so if anyone needs it maybe it will help
//model
postItemsToItemCategory: function (setData, cb) {
db.query('INSERT INTO data_categories ( data_id, category_id) VALUES (?, ?)', [setData.data_id, setData.category_id], cb)
}
and I found the problem I'm not careful to not put the await and change the for of into forEach
postItemData: async function (req, res) {
const setData = req.body
try {
if (setData.price < 1) {
return helper.response(res, 'fail', 'Cannot type number below 1', 400)
}
const result = await itemModels.postItems(setData)
if (typeof setData.category_id !== 'object') {
setData.category_id = [setData.category_id]
}
await setData.category_id.forEach((categoryId) => {
const categoryData = {
data_id: result.insertId,
category_id: categoryId
}
postItemsToItemCategory(categoryData, () => {
console.log(`product ${result.insertId} has been created on category ${categoryId}!`)
})
})
return helper.response(res, 'success', result, 200)
} catch (err) {
console.log(err)
return helper.response(res, 'fail', 'Internal Server Error!', 500)
}
}
I ran into an issue with an axios post request
const addOrder = (newOrder) => {
axios
.post("http://localhost:83/api/addorder", {
newRow: newOrder,
newRecID: orders[0].RecID + 1,
})
.then((response) => {
console.log(response);
getOrders();
})
.catch((err) => {
console.log("Err", err);
});
In my API the request handler is this:
app.post("/api/addorder", function (req, res) {
const newData = req.body.newOrder;
let newRecID = req.body.newRecID;
sql.connect(config, function (err) {
if (err) {
console.log(err);
return;
}
var request = new sql.Request();
request.query(
`INSERT INTO dbo.Einkauf_Web_Bestellungen_DEV (RecID) VALUES (${newRecID})`,
function (err, result) {
if (err) {
console.log(err);
}
}
);
});
});
The SQL Query is executed and succesfully inserts the given value. But my react application crashes and spits out following error:
Screenshot of the application console
So I come to this, I want to write into a DB and do other operations to work with my program logic, this is the guide that I'm following Node.js Class Creation:
//## This is my mysql_test.js file
function MySQL(){
var mysql = require('mysql');
var con = mysql.createConnection({
//data omitted
});
function AppendRecordset (req, res){
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query(req, function (err, res) {
if (err) throw err;
console.log("1 record inserted");
});
});
}
function UpdateRecordset (req, res) {
con.connect(function(err) {
if (err) throw err;
con.query(req, function (err, res) {
if (err) throw err;
console.log(result.affectedRows + " record(s) updated");
});
});
}
function DeleteRecordset (req, res){
con.connect(function(err) {
if (err) throw err;
con.query(req, function (err, res) {
if (err) throw err;
console.log("Number of records deleted: " + result.affectedRows);
});
});
}
function GetRecordset (req, res) {
con.connect(function(err) {
if (err) throw err;
con.query(req, function (err, res, fields) {
if (err) throw err;
console.log(result);
});
});
}
}
I then have in a separate file(s) my app logic, and want to use what of the above as an object/class so I wrote this accordingly to that guide:
//##this is inside my main app file
//declare the sql processor
require('./mysql_test.js');
var DB = MySQL();
DB.AppendRecordset(sql_string, res); //sql_string contains a valid SQL statement
But when I try to acces it using `` I get this error message: ReferenceError: MySQL is not defined what am I doing wrong?
I think these functions handle your routes, so I didn't change them. Because I don't know how your router is desined.
Create a file dbHangler.js and write this single function:
const mysql = require('mysql');
let con;
exports.execQuery = (query) => {
return new Promise((resolve, reject) => {
if(!con) {
con = mysql.createConnection({
//data omitted
});
}
con.connect(function(err) {
if(err) {
reject(err);
}
else {
console.log("Connected!");
con.query(query, function (err, res) {
if (err) {
reject(err);
}
else {
resolve(res);
}
});
}
});
});
};
In your dedicated.js file, now you can write:
const dbObject = require('path/to/dbHandler');
function AppendRecordset (req, res){
dbObject.execQuery(req)
.then(result => {
console.log(result.affectedRows + " record(s) updated");
})
.catch(error => {
// handle error
});
}
function AppendRecordset (req, res){
dbObject.execQuery(req)
.then(result => {
console.log("Number of records deleted: " + result.affectedRows);
})
.catch(error => {
// handle error
});
}
function AppendRecordset (req, res){
dbObject.execQuery(req)
.then(result => {
console.log(result);
})
.catch(error => {
// handle error
});
}
UPDATE
I hope this one helps you.
DbHandler.js
const mysql = require('mysql');
class DbHandler {
constructor(config) {
let self = this;
self.dbConfig = config;
self.connection = mysql.createConnection({
//data omitted
});
}
queryExecuter(query) {
let self = this;
return new Promise((resolve, reject) => {
self.connection.connect(function (err) {
if (err) {
reject(err);
}
else {
console.log("Connected!");
self.connection.query(query, function (err, res) {
if (err) {
reject(err);
}
else {
resolve(res);
}
});
}
});
});
}
AppendRecordset(query) {
let self = this;
return self.queryExecuter(query)
.then(result => {
console.log("1 record inserted");
return result;
})
.catch(error => {
// handle error
throw error;
});
}
UpdateRecordset(query) {
let self = this;
return self.queryExecuter(query)
.then(result => {
console.log(result.affectedRows + " record(s) updated");
return result;
})
.catch(error => {
// handle error
throw error;
});
}
// and other functions
}
module.exports = DbHandler;
And use it like below:
let DB = require('/path/to/DbHandler');
let myDb = new DB(/* db config */);
db.UpdateRecordset('your query')
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
I'm creating my first app using Node.js and PostgreSQL.
This app connect's to db and return record to browser in JSON format, its work perfectly till i try to use map function to formating properties.
When i use map it return an error:
TypeError: rows.map is not a function
This is my code.
app.get('/car/:id', (req, res) => {
const car_id = req.params.id;
const queryString = `SELECT * FROM cars WHERE car_id= ${car_id}`;
client.query(queryString, (err, rows, fields) => {
if (err) {
console.log(err.stack);
res.sendStatus(500);
res.end();
} else {
const car = rows.map((row) => {
return {"Car_ID": row.car_id}
});
res.json(car);
console.log(rows.rows);
}
});
It should be result.rows not just rows
According to this - https://node-postgres.com/api/result
app.get('/car/:id', (req, res) => {
const car_id = req.params.id;
const queryString = `SELECT * FROM cars WHERE car_id= ${car_id}`;
client.query(queryString, (err, result, fields) => {
if (err) {
console.log(err.stack);
res.sendStatus(500);
res.end();
} else {
const car = result.rows.map((row) => {
return {"Car_ID": row.car_id}
});
res.json(car);
console.log(result.rows);
}
});
I am not sure how to pass data to a promise function like below.
I need to parss it a JSON object that is then used in my MSSQL query, but if i remove the function around the promise, it says that data is undefined.
The code below is functional, I am just looking for a cleaner way to do this.
routes.post('/save', function(req, res){
var insert = function(data) {
sql.connect(config)
.then(pool => {
return pool.request()
.input('first_name', sql.VarChar(100), data.firstName)
.input('last_name', sql.VarChar(100), data.lastName)
.query('INSERT INTO Uncomplete_registration (first_name, last_name) VALUES (#first_name, #last_name)')
}).then(result => {
console.dir(result)
}).catch(err => {
console.dir(err)
})
sql.on('error', err => {
console.dir("other error: " + err);
})
}
insert(req.body.data);
});
I am sure there is a better way to do this but I am not sure how...
Try this
routes.post('/save', function(req, res){
var data = req.body.data;
sql.connect(config)
.then(pool => {
return pool.request()
.input('first_name', sql.VarChar(100), data.firstName)
.input('last_name', sql.VarChar(100), data.lastName)
.query('INSERT INTO Uncomplete_registration (first_name, last_name) VALUES (#first_name, #last_name)')
}).then(result => {
console.dir(result)
}).catch(err => {
console.dir(err)
})
sql.on('error', err => {
console.dir("other error: " + err);
})
});
This makes data into a local variable, which is essentially what your function is doing. The promise .then/.catch can then access it as a closure variable.
routes.post("/save", function (req, res) {
var data = req.body.data;
sql.connect(config)
.then(pool => {
return pool.request()
.input("first_name", sql.VarChar(100), data.firstName)
.input("last_name", sql.VarChar(100), data.lastName)
.query("INSERT INTO Uncomplete_registration (first_name, last_name) VALUES (#first_name, #last_name)");
}).then(result => {
console.dir(result);
}).catch(err => {
console.dir(err);
});
sql.on("error", err => {
console.dir("other error: " + err);
});
});