I'm trying out Node.js and sqlite database work and have come across this and I am currently stuck.
my console error is:
TypeError: data is not iterable
at db.all (C:\Users\Taylor\Desktop\book\index1.js:30:22)
at Statement.errBack (C:\Users\Taylor\node_modules\sqlite3\lib\sqlite3.js:16:21)
--> in Database#all('SELECT id, title FROM Jobs;', [Function])
at app.get (C:\Users\Taylor\Desktop\book\index1.js:26:6)
at Layer.handle [as handle_request] (C:\Users\Taylor\Desktop\book\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Taylor\Desktop\book\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\Taylor\Desktop\book\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\Taylor\Desktop\book\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Taylor\Desktop\book\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\Taylor\Desktop\book\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\Taylor\Desktop\book\node_modules\express\lib\router\index.js:275:10)
at urlencodedParser (C:\Users\Taylor\Desktop\book\node_modules\body-parser\lib\types\urlencoded.js:91:7)
this is my js script:
app.get('/', async(req, res) => {
const sql = 'SELECT id, title FROM Jobs;'
console.log(sql)
db.all(sql, (err, data) => {
if(err) console.error(err.message)
console.log(data)
let list = '<ol>'
for(const job of data) {
console.log(job.title)
list += `<li>${job.title}</li>`
}
list += '</ol>'
console.log(list)
res.render('index', {locals: {Jobs: list}})
})
})
Related
I am trying to insert a row of values into MySQL database using Knex but I am getting a weird error. The table and database exist and the fetch API works perfectly but I am not able to insert values using sifnUp route.
const db= knex ({
client: 'mysql2',
connection: {
host: '127.0.0.1',
port: 3306,
user: 'root',
password: '',
database: 'transaction_app'
}
});
app.get('/', (req, res) => {
res.send('App is running')
});
app.post('/signUp', (req, res,db) => {
const {name, email, mobile, password}=req.body;
const hash=bcrypt.hashSync(password, 10);
db('users')
.insert({
name: name,
email: email,
mobile: mobile,
password: hash
})
.then(data=>{
res.send(data);
})
.catch(err=>{
res.send(err);
})
});
app.get('/fetch',(req,res)=>{
db.select('*').from('users')
.then(data=>{
res.send(data);
})
.catch(err=>{
res.send(err);
})
})
app.listen(3000, () =>{
console.log('Server started on port 3000');
});
The error that is consoled is this
Server started on port 3000
users
TypeError: Cannot read properties of undefined (reading 'insert')
at D:\Documents\Atoa Assignment\server.js:35:3
at Layer.handle [as handle_request] (D:\Documents\Atoa Assignment\node_modules\express\lib\router\layer.js:95:5)
at next (D:\Documents\Atoa Assignment\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (D:\Documents\Atoa Assignment\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (D:\Documents\Atoa Assignment\node_modules\express\lib\router\layer.js:95:5)
at D:\Documents\Atoa Assignment\node_modules\express\lib\router\index.js:284:15
at Function.process_params (D:\Documents\Atoa Assignment\node_modules\express\lib\router\index.js:346:12)
at next (D:\Documents\Atoa Assignment\node_modules\express\lib\router\index.js:280:10)
at cors (D:\Documents\Atoa Assignment\node_modules\cors\lib\index.js:188:7) at D:\Documents\Atoa Assignment\node_modules\cors\lib\index.js:224:17
This is the Postman Screenshot.
Your error:
app.post('/signUp', (req, res,db) => {
const {name, email, mobile, password}
The third parameter is the express next, not db.
Inside the route you assign next() to db. (req,res,"db")
Must be (req,res, next).
When you call db.insert it is not referring of the top of your code
const db= knex ({
So you dont db.insert but next.insert (which obviously does not exist).
As you are not using the next handler of express, simply delete db in (req,res,db) and it should work.
Remember the scopes of variables in Javascript.
An Example
I am not able to insert data to the database. There is no issues connected to the database but when I try to insert into table, It through an error.
Error: Cannot enqueue Query after fatal error.
How can I solve this problem? Anyone facing same problem?
const { redirect } = require("express/lib/response");
const mysql = require('mysql')
let con = mysql.createConnection({
host: process.env.db_host,
database: process.env.db_database,
username: process.env.db_username,
password: process.env.db_password,
port: process.env.db_port
});
con.connect(err=>{
{err===true? console.log(err): console.log("DB connected Successfully!!");;}
})
// Home Page
exports.index = (req,res)=>{
res.render('../views/index', {btnName: 'Save' })
console.log("You are in home page!");
}
// // Add User
// exports.addUser = (req,res)=>{
// res.render('adduser')
// }
exports.adduserpost = (req,res)=>{
const {fname, mname, lname, email, phone} = req.body; //store value from adduser
// console.log({fname, mname, lname, email, phone});
let sql = 'INSERT INTO user_info (fname, mname, lname, email, phone) VALUES (?,?,?,?,?)';
con.query(sql,[fname, mname, lname, email, phone],
(err,result)=>{
if(!err) console.log(result);
else console.log( err);
})
Through Error like this.
Server connected successfully!!
DB connected Successfully!!
Error: Cannot enqueue Query after fatal error.
at Protocol._validateEnqueue (F:\Project\User_Information_System_v2\node_modules\mysql\lib\protocol\Protocol.js:212:16)
at Protocol._enqueue (F:\Project\User_Information_System_v2\node_modules\mysql\lib\protocol\Protocol.js:138:13)
at Connection.query (F:\Project\User_Information_System_v2\node_modules\mysql\lib\Connection.js:198:25)
at exports.adduserpost (F:\Project\User_Information_System_v2\server\controller\userController.js:53:5)
at Layer.handle [as handle_request] (F:\Project\User_Information_System_v2\node_modules\express\lib\router\layer.js:95:5)
at next (F:\Project\User_Information_System_v2\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (F:\Project\User_Information_System_v2\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (F:\Project\User_Information_System_v2\node_modules\express\lib\router\layer.js:95:5)
at F:\Project\User_Information_System_v2\node_modules\express\lib\router\index.js:281:22
at Function.process_params (F:\Project\User_Information_System_v2\node_modules\express\lib\router\index.js:341:12) {
code: 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR',
fatal: false
}
You should change your connect error checking condition.
By using err===true the message DB connected Successfully!! will be displayed also if the err is present as an object.
Try to change your code like this and see if it logs any error messages:
con.connect(err=>{
if(err) {
console.log(err);
process.exit(1);
}
console.log("DB connected Successfully!!")
})
Here is the code :
application.post('/Modification/SaveEdit/:idd',function(req,res){
var mem = req.body.memo;
connection.query('UPDATE memos SET textMemo = ?',mem,'WHERE idMemo = ?',req.params.idd, function (error, results, fields){
if (error) {
console.log("error ocurred",error);
res.send({
"code":400,
"failed":"erreur survenue"
})
}else{
console.log('Resultats: ', results);
res.send({
"code":200,
"success":"votre memo est bien modifié ! "
});
}
});
});
i think it's the syntax of my query but i don't know how to write it correctly .
Here is the error :
TypeError: argument callback must be a function when provided
at Function.createQuery (/home/mohand/node_modules/mysql/lib/Connection.js:57:13)
at Connection.query (/home/mohand/node_modules/mysql/lib/Connection.js:181:26)
at /home/mohand/TpsWEB/DMajour/expreServer.js:146:13
at Layer.handle [as handle_request] (/home/mohand/node_modules/express/lib/router/layer.js:95:5)
at next (/home/mohand/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/mohand/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/mohand/node_modules/express/lib/router/layer.js:95:5)
at /home/mohand/node_modules/express/lib/router/index.js:281:22
at param (/home/mohand/node_modules/express/lib/router/index.js:354:14)
at param (/home/mohand/node_modules/express/lib/router/index.js:365:14)
Thank's in advance !
I suspect that you might be using the connection.query incorrectly. Maybe check up on the docs for that (https://github.com/mysqljs/mysql#performing-queries). You are providing it with 5 arguments, but it should only have at most 3. Try the following:
application.post('/Modification/SaveEdit/:idd',function(req,res){
var mem = req.body.memo;
connection.query('UPDATE memos SET textMemo = ? WHERE idMemo = ?',[mem,req.params.idd], function (error, results, fields){
if (error) {
console.log("error ocurred",error);
res.send({
"code":400,
"failed":"erreur survenue"
})
}else{
console.log('Resultats: ', results);
res.send({
"code":200,
"success":"votre memo est bien modifié ! "
});
}
});
});
When I send the first request after starting the server, it's okay.
But after updating the page (re-query), you receive an error:
app.get('/images', function(req, res, next) {
if (connection.state === 'disconnected'){
connection.connect();}
else {
}
var DATABASE='nodejsImage';
var results;
connection.query('use ' + DATABASE);
connection.query('SELECT `id`, `imagename`, `filename`, `speed`, `move` FROM `images` WHERE 1',
function (err, results, fields) {
if (err) return console.log("Error test") //throw err;
else {
console.log('Images list');
console.log('----------------------------------');
for (var i in results) {
var gadget = results[i];
console.log(gadget.id +': '+ gadget.imagename+': '+gadget.speed+': '+gadget.move);
}
res.render('imagelist', { title: 'Imagelist',listImages:results });
}
});
connection.end(); //разобраться с ошибкой позже!!!
});
Error message:
events.js:165
throw er; // Unhandled 'error' event
^
Error: Cannot enqueue Handshake after invoking quit.
at Protocol._validateEnqueue (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\mysql\lib\protocol\Protocol.js:204:16)
at Protocol._enqueue (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\mysql\lib\protocol\Protocol.js:139:13)
at Protocol.handshake (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\mysql\lib\protocol\Protocol.js:52:23)
at Connection.connect (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\mysql\lib\Connection.js:118:18)
at E:\Dropbox\untitled5-upload-3\untitled5\app.js:48:16
at Layer.handle [as handle_request] (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\express\lib\router\layer.js:95:5)
at next (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\express\lib\router\layer.js:95:5)
at E:\Dropbox\untitled5-upload-3\untitled5\node_modules\express\lib\router\index.js:281:22
Emitted 'error' event at:
at Connection._handleProtocolError (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\mysql\lib\Connection.js:425:8)
at Protocol.emit (events.js:180:13)
at Protocol._delegateError (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\mysql\lib\protocol\Protocol.js:392:10)
at Handshake.<anonymous> (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\mysql\lib\protocol\Protocol.js:221:10)
at Handshake.emit (events.js:180:13)
at Handshake.Sequence.end (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:12)
at E:\Dropbox\untitled5-upload-3\untitled5\node_modules\mysql\lib\protocol\Protocol.js:225:14
at process._tickCallback (internal/process/next_tick.js:112:11)
It are easy way to add pass items
to view.
var imageList = [];
// Connect to MySQL database.
var connection = getMySQLConnection();
connection.connect();
// Do the query to get data.
connection.query('SELECT * FROM images', function(err, rows, fields) {
if (err) {
res.status(500).json({"status_code": 500,"status_message": "internal server error"});
} else {
// Loop check on each row
for (var i = 0; i < rows.length; i++) {
// Create an object to save current row's data
var person = {
'id':rows[i].id,
'imagename':rows[i].imagename,
'filename':rows[i].filename,
'speed':rows[i].speed,
'move':rows[i].move
}
// Add object into array
imageList.push(person);
}
// Render index.pug page using array
res.render('imagelist', { title: 'Imagelist',listImages:imageList });
}
});
// Close the MySQL connection
connection.end();
I have a route
router.post('/api/getSessionTimeOut', apiController.getSessionTimeOut);
This is in my controller
function getSessionTimeOut(req, res) {
res.send(req.body.session); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
var options =
{
method: 'POST',
url: 'http://api/json',
body:
{
id: 1,
method: 'get',
params: [
{
url: '/cli/global/system/admin/setting'
}
],
session: req.params.session
},
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body, response);
res.send(response.result);
});
};
After making a POST to the route with session as body via Postman
I kept getting
Red alert! Red alert!: TypeError: Cannot read property 'session' of undefined
at getSessionTimeOut (/Users/doe/Desktop/express-app/controllers/api.js:50:23) at Layer.handle [as handle_request] (/Users/doe/Desktop/express-app/node_modules/express/lib/router/layer.js:95:5) at next (/Users/doe/Desktop/express-app/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/Users/doe/Desktop/express-app/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/Users/doe/Desktop/express-app/node_modules/express/lib/router/layer.js:95:5) at /Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:281:22 at Function.process_params (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:335:12) at next (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:275:10) at Function.handle (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:174:3) at router (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:47:12) at Layer.handle [as handle_request] (/Users/doe/Desktop/express-app/node_modules/express/lib/router/layer.js:95:5) at trim_prefix (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:317:13) at /Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:284:7 at Function.process_params (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:335:12) at next (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:275:10) at serveStatic (/Users/doe/Desktop/express-app/node_modules/serve-static/index.js:75:16) at Layer.handle [as handle_request] (/Users/doe/Desktop/express-app/node_modules/express/lib/router/layer.js:95:5) at trim_prefix (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:317:13) at /Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:284:7 at Function.process_params (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:335:12) at next (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:275:10) at expressInit (/Users/doe/Desktop/express-app/node_modules/express/lib/middleware/init.js:40:5)
index.js
import express from 'express'
import favicon from 'serve-favicon'
import path from 'path'
import bodyParser from 'body-parser'
// Controllers
import apiController from './controllers/api'
const router = express.Router();
const app = express();
const PORT = 3000;
//For public folder
app.use(express.static('public'))
app.use(router)
app.use('/images',express.static('images'))
app.use(favicon(path.join(__dirname,'public','favicon.ico')))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
router.get('/', (req,res) => {
res.send('Welcome to the backend provisioning daemon to program FortiManager')
});
// app.use( express.json());
app.use(express.urlencoded({extended: true}))
app.set('trust proxy', 'loopback');
//Fortinet
router.post('/api/getSessionTimeOut', apiController.getSessionTimeOut);
router.post('/api/login', apiController.login);
//Error handling function
app.use((err,req,res,next) => {
console.error(err.stack)
res.status(500).send(`Red alert! Red alert!: ${err.stack}`)
});
// app listen
app.listen(PORT, () => {
console.log(`Your server is running on ${PORT}`)
}
);
Try moving
app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true }));
right after
const app = express();
Why, because you need to use/register middlewares on your server/app before registering any route on your server. This will make sure that every request coming to the registered route is first passed through body-parsers and will let the body-parsers to do the construct the request data in its specified data structure or format.
Hope that helps
Thanks