update query in sqlite failed - sql

I send my object by post request with postman then in the backend with node js recive it and update my table but it return sqlerror on string in object and no problem on integer !
1 - my obj in postman => {
"id" : 3,
"controlsCode":123456,
"controlsName" : "hamed"
}
2 - my code in node =>
async editControls(req, res) {
try {
const { id, controlsCode, controlsName } = req.body;
const query = `update controls set controlCode=${controlsCode} , controlName=${controlsName} where id =${id}`;
await sequelize
.query(query)
.then((item) =>
this.response({ res, message: "ok", data: controlsCode })
)
.catch((error) => console.log(error.message));
} catch (error) {
console.log(error.message);
}
}
3-error in node js =>
SQLITE_ERROR: no such column: hamed

You need single quotes around the string literal:
try {
const { id, controlsCode, controlsName } = req.body;
const query = `update controls set controlCode=${controlsCode} , controlName='${controlsName}' where id =${id}`;
await sequelize
.query(query)
.then((item) =>
this.response({ res, message: "ok", data: controlsCode })
)
.catch((error) => console.log(error.message));
} catch (error) {
console.log(error.message);
}

Related

express path issues when using same logic on diffrent paths

id path is working (I get the result from the json), but even though pokeName uses the same logic, I dont get any data from it. What have we missed?
JSON: https://github.com/Biuni/PokemonGO-Pokedex/blob/master/pokedex.json
const Pokemons = mongoose.model('Pokemons', {
id: Number,
name: String,
type: Array,
})
_____
app.get('/pokemons', async (req, res) => {
try {
if (!allPokemons) {
res.status(404).send('No data to show')
} else {
res.json(allPokemons.pokemon) /*[1].name*/
}
} catch (error) {
res.status(400).json({ error: 'Not found' })
}
})
_____
app.get('/pokemons/id/:id', async (req, res) => {
const { id } = req.params
const pokemon = allPokemons.pokemon.find((item) => item.id === +id)
try {
if (!pokemon) {
res.status(404).send('No pokemon found with this ID')
} else {
res.json(pokemon)
}
} catch (error) {
res.status(400).json({ error: 'Not found' })
}
})
_____
app.get('/pokemons/name/:pokeName', async (req, res) => {
const { pokeName } = req.params
const pokemon = allPokemons.pokemon.find((item) => item.name === +pokeName)
try {
if (!pokemon) {
res.status(404).send('No pokemon found with this name')
} else {
res.json(pokemon)
}
} catch (error) {
res.status(400).json({ error: 'Not found' })
}
})
You're trying to convert the name to a number (presumably because id is a number, and you copied its code):
item.name === +pokeName
But it's not, so this will result in a NaN. Remove the +:
item.name === pokeName

get logged in ID from jwt so that only logged in user can see particular data in nodejs

I am using nodejs, jwt and mysql.
I want the current logged in user ID soo that I can show the data respective to it.
This is my code where SQL logic is written and here I am expecting to get a current user ID.
const pool = require('../../dbconfig/dbconfig');
module.exports = {
getProfile : (callBack) => {
var sql = 'SELECT name, shopStatus, phone, shopaddress.shopNo, shopaddress.complex, shopaddress.landmark, shopaddress.street, shopaddress.area, shopaddress.city FROM shop INNER JOIN shopaddress ON shop.id = shopaddress.shop_id WHERE shop.id = ?'
var insertSql = [ /* how can i get ID here.. */ ]
pool.query(sql, insertSql, (err, results, fields) => {
if(err) {
return callBack(err)
}
return callBack(null, results)
})
}
}
this happens to be jwt middleware code
const jwt = require('jsonwebtoken')
const config = require('../../config')
module.exports = {
isAuth: (req, res, next) => {
let token = req.get("authorization");
if (token) {
// Remove Bearer from string
token = token.slice(7);
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
return res.json({
status: 'error',
message: "Invalid Token..."
});
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.json({
status: 'error',
message: "Access Denied! Unauthorized User"
});
}
}
};
and this is controller
const shopService = require('./shop.service')
module.exports = {
shopProfile : (req, res) => {
shopService.getProfile((err, results) => {
if(err){
return res.status(500).json({
status : 'error',
error : err,
message : 'Database connection error'
})
}
return res.status(200).json({
status:'success',
data : results
})
})
}
}

Sqlite3 returning empty array with GET request in Express

I am trying to make a get request to an sqlite3 table, using Express, based on input from a form. The fetch request works and so does the db.all, but I receive a response as an empty array from rows. I tried req.query and req.params already. Not sure where the error is.
//server.js
app.get('/names/state', (req, res, next) => {
const stateValue = req.query.state;
db.all(`SELECT name FROM states WHERE name=$stateVal`,
{
$stateVal: stateValue
},
(err, rows) => {
res.send({rows:rows});
})
});
//script.js
const fetchOneBtn = (e) => {
e.preventDefault();
const stateVal = stateInputValue.value;
fetch(`/names/state?state=${stateVal}`)
.then(response =>{
if(response.ok){
return response.json();
}
}).then(names => {
console.log(names);
})
};
You can change your code in your backend with this code below:
app.get('/names/state', (req, res, next) => {
const stateValue = req.query.state;
var query = "SELECT name FROM states WHERE name = " + stateValue;
db.all(query, (err, rows) => {
if(err) {
console.log(err);
res.status(500).send(err);
}else {
res.send({rows});
}
})
});
Now, for your frontend, you can change with the code below:
const fetchOneBtn = async (e) => {
e.preventDefault();
const stateVal = stateInputValue.value;
try {
const response = await fetch(`/names/state?state=${stateVal}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
});
console.log(await response.json());
return await response.json();
} catch(ex) {
console.log(ex);
}
};
I hope it can help you.

Send single response after multiple updates

I have an array of items that I am passing to an API endpoint (using Sequelize as my ORM). I'm trying to iterate over each item and update it, however I'm getting a Unhandled rejection Error: Can't set headers after they are sent.
stepsController.put = (req, res) => {
const { steps } = req.body;
// Steps is an array of objects that I want to update...
steps.map(step => {
Step.findOne({ where: { id: step.id } })
.then(savedStep =>
savedStep
.update({
order: step.order,
})
.then(success => res.status(200).send(success))
.catch(error => res.send(error))
)
.then(ok => res.status(200).send(ok))
.catch(err => res.send(err));
});
};
I believe this is because it's sending the response for each item. Sequelize's update method is a promise. How can I iterate over all of the items and make sure all of the items are updated before sending a single successful response?
There are three ways you can do
Promise.all
Co
Async Await
1) Here it is , you can use Promise.all :
stepsController.put = (req, res) => {
const { steps } = req.body;
// Steps is an array of objects that I want to update...
Promise.all(steps.map(step => {
return Step.findOne({ where: { id: step.id } }).then(savedStep =>
return savedStep.update({
order: step.order,
})
.catch(error => error)
).catch(err => err)
}))
.then(ok => res.status(200).send(ok))
.catch(err => res.send(err));
};
2) Another way is to use co :
const co = require('co');
stepsController.put = co.wrap(function* (req, res) => {
try {
const { steps } = req.body;
// Steps is an array of objects that I want to update...
for(let i=0;i<steps.length ; i++) {
let savedStep = yield Step.findOne({ where: { id: steps[i].id } });
if(savedStep)
yield savedStep.update({ order: steps[i].order});
}
res.status(200).send();
}
catch(err){
res.send(err);
}
});
3) If you’re using Node 8.0+ , there is no need of any package you can directly use async await :
stepsController.put = async(req, res) => {
try {
const { steps } = req.body;
// Steps is an array of objects that I want to update...
for(let i=0;i<steps.length ; i++) {
let savedStep = await Step.findOne({ where: { id: steps[i].id } });
if(savedStep)
await savedStep.update({ order: steps[i].order});
}
res.status(200).send();
}
catch(err){
res.send(err);
}
};

Express API - select one id from database

i want to know how can i realize passing parameter to Model. I have 3 file server.js , controllers/news.js and models/news.js
Server.js
const newsController = require('./controllers/news');
server.get('/newsAll', newsController.all);
server.post('/getOneNews', (req, res) => {
db.get().query(`SELECT * FROM news WHERE id = ?`, [ req.body.id ],
(err, result, fields) => {
if (err) console.log('error SELECT one row', err);
});
});
controller/news.js
const newsModule = require('../models/news');
exports.all = (req, res) => {
newsModule.all((err, rows) => {
if (err) {
console.error(err);
return res.sendStatus(500);
}
res.send(rows);
});
};
models/news.js
const db = require('../db');
exports.all = (done) => {
db.get().query(`SELECT * FROM news ORDER BY id`, (err, rows) => {
if (err) {
console.log('error SELECT * FROM news MYSQL', err);
throw err;
}
done(err, rows);
});
};
All about method all i understood , but i want to know how can i passing [ req.body.id ] (<- from front-end) this parametr to Model for accepting ONE news from database . Whithout parameters it is very easy.
All you need is to do is grab the id from the req.params object and then set your endpoint to accept that params value.
// Server.js
server.get('/getOneNews/:id', (req, res) => {
db.get().query(`SELECT * FROM news WHERE id = ?`, [ req.params.id ],
(err, result, fields) => {
if (err) console.log('error SELECT one row', err);
});
});
Hope this helps!