Command Shot
Above I have a screen shot of my app.js server and for some reason the connection is not going through below I have my app.js code
const express = require('express');
const app = express();
const mysql = require('mysql');
const bodyparser = require('body-parser');
app.use(bodyparser.json());
const mysqlConnection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'Adil#123',
database: 'movies'
});
mysqlConnection.connect(err=>{
if (err) {
console.log('It was not successful \n Error:' + JSON.stringify(err,undefined,2));
} else {
console.log('Its a success');
}
});
// Collecting all the movies from the movielist
app.get('/movielist',(req,res)=> {
mysqlConnection.query("SELECT * FROM movielist", (err, rows,fields)=> {
if (!err) {
res.send(rows);
} else {
console.log(err);
}
});
});
// Finding a movie based on the `idmovielist` number
app.get('/movielist',(req,res) => {
mysqlConnection.query("SELECT * FROM movielist WHERE idmovielist = ?",[req.params.id],(err, rows,fields) =>{
if (!err) {
res.send(rows);
} else {
console.log(err);
}
});
});
// Delting a movie
app.delete('/movielist/:id',(req,res) => {
mysqlConnection.query("DELETE FROM movielist WHERE idmovielist = ?",[req.params.id],(err,rows,fields) =>{
if (!err) {
res.send("Movie is deleted");
} else {
console.log(err);
}
});
});
// Inserting a movie
app.post('/movielist/addMovie',(req, res) => {
mysqlConnection.query("INSERT INTO movielist (`idmovielist`,`name`,`thumnail_path`,`description`,`language_released`,`year_released`) VALUES ('"+req.body.idmovielist+"', '"+req.body.name+"','"+req.body.thumnail_path+"', '"+req.body.description+"', '"+req.body.year_released+"', '"+req.body.language_released+"' )",
(err,rows) => {
if (!err) {
res.send("Movie is added");
} else {
console.log(err);
}
});
});
// Updating the movie list
app.put('/movielist/:id',(req,res) =>{
let update = req.body;
mysqlConnection.query("UPDATE movielist SET `year_released` WHERE = '"+update.idmovielist+"','"+update.year_released+"'",
(err, results) => {
if (!err) {
res.send("Movie list is updated");
} else {
console.log(err);
}
});
});
// localhost:3000
app.listen(3000,() => {
console.log('We got it running');
});
module.exports = app;
Above is my app.js the server was working earlier but for some reason it is not working anymore what can be the issue Is it something wrong with my code or should I change the port or create another server
Related
I don't know what I am doing wrong, however the following is not working.
I have the database connecting however when I try and use the connection it won't let me.
index.js
config = require('./config');
const express = require('express');
const app = express();
const mDB = require('./components/mongodb').connect(config.dbUri);
app.get('/testDB', (req,res) =>{
const user = { name: 'John', age: 30 };
mDB.insertOne(user, (error, result) => {
if (error) {
console.log(error);
return;
}
console.log(`Successfully inserted user: ${result.insertedId}`);
res.send("inserted");
});
});
app.listen(3000, () => {
console.log('App listening on port 3000');
});
./components/mongodb.js
const MongoClient = require('mongodb').MongoClient;
module.exports.connect = (uri) => {
MongoClient.connect(uri, { useNewUrlParser: true }, (err, client) => {
if (err) {
console.error(`MongoDB connection error: ${err}`);
process.exit(1);
}
console.log('Successfully connected to MongoDB');
module.exports.client = client;
});
};
module.exports.insertOne = (collection, document) => {
module.exports.client.db('PodToo').collection(collection).insertOne(document, (error, result) => {
if (error) {
console.log(error);
return;
}
console.log(`Successfully inserted document: ${result.insertedId}`);
});
};
I get the Successfully connected to MongoDB
But then when I try and use it I am receiving
TypeError: Cannot read properties of undefined (reading 'insertOne')
In the danger of stating the obvious: You are missing the first argument to your insertOne function, the collection name.
Did you mean
mDB.insertOne('users', user, ...
?
I am New To async/await coding in node js. I am trying to fetch data from mysql and then populate the result into an object. But i am not finding a way how to do it in controller.js file.
My source code similar to this.
My Router File
const express = require("express");
const controller = require("controller");
const router = express.Router();
router.route("/").get(controller.findAll);
My Controller File
const model = require("model");
exports.findAll = async (req, res) => {
const all = model.getAll((err, data) => {
if (err) {
res.status(500).send({
message: err.message || "Some error occurred while retrieving data.",
});
}
return data;
});
const user = model1.getUser((err, data) => {
if (err) {
res.status(500).send({
message: err.message || "Some error occurred while retrieving user.",
});
}
return data;
});
// somefunctionality(all, user);
// res.send(result);
};
My Model file
const con = require("./db");
// constructor
const Customers= function (customer) {
this.id = customer.id;
this.first_name = customer.first_name;
this.last_name = customer.last_name;
this.email = customer.email;
};
Customers.getAll = () => {
const query = `SELECT * FROM doctors`;
sql.query(query, (err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
console.log("customers: ", res);
result(null, res);
};
user model same as customer
Thanks for your help
The first thing I would do is covert your Customers.getAll method to return a promise:
model file
Customers.getAll = () => {
const query = `SELECT * FROM doctors`;
return new Promise((res, rej) => {
sql.query(query, (err, data) => {
if (err) {
console.log("error: ", err);
rej(err);
return;
}
console.log("customers: ", res);
res(data);
})
};
(Note that you'll probably have to do something similar to the getAll method for your User model)
Now, in the controller, you can use try/catch to handle any errors.
*controller file
exports.findAll = async (req, res) => {
try {
const all = await model.getAll();
const users = await model1.getUser();
const result = somefunctionality(all, user);
res.send(result);
} catch(err) {
res.status(500).send({
message: err.message || "Some error occurred while retrieving data.",
});
}
};
I am new in nodejs. I am creating a basic API to get record by id. Everything is working fine. It is returning user data from database. But when i use password variable from response in same function it give me empty value whereas i am getting value in response. I think this is async issue but i dont know how to fix it.
This is API code
var express = require('express');
var db = require('../db/database');
var bcrypt = require('bcrypt');
const router = express.Router();
router.get("/:userId", (req, res, next) => {
let uid = req.params.userId;
db.query(`SELECT * FROM users WHERE u_id = ${uid}`, (err, data)=> {
if(!err) {
if(data && data.length > 0) {
var message = '';
if(data.u_password){
//var pass = data.u_password;
if(bcrypt.compare('123456', data.u_password)) {
// Passwords match
message = 'Passwords match';
} else {
// Passwords don't match
message = 'Passwords dont match';
}
}
res.status(200).json({
message:message,
});
} else {
res.status(200).json({
message:"User Not found."
});
}
}
});
});
database.js
var mysql = require('mysql');
const pool = mysql.createPool({
connectionLimit : 10,
host: 'localhost',
user: 'root',
password: '',
database: 'lost_and_found',
debug : false
});
function executeQuery(sql, callback) {
pool.getConnection((err,connection) => {
if(err) {
return callback(err, null);
} else {
if(connection) {
connection.query(sql, function (error, results, fields) {
connection.release();
if (error) {
return callback(error, null);
}
return callback(null, results);
});
}
}
});
}
function query(sql, callback) {
executeQuery(sql,function(err, data) {
if(err) {
return callback(err);
}
callback(null, data);
});
}
module.exports = {
query: query
}
Response
{"message":""}
Please change the bcrypt.compare code to following code. It is a callback function:
bcrypt.compare('123456', data.u_password, function(err, result) {
if (err) {
// Passwords don't match
message = 'Passwords dont match';
} else {
// Passwords match
message = 'Passwords match';
}
res.status(200).json({
message:message,
});
})
EDIT 1: Please update the method to following logic:
db.query(`SELECT * FROM users WHERE u_id = ${uid}`, (err, data) => {
if (err) {
throw err;
}
if (data && data.length > 0) {
var message = '';
if (data.u_password) {
bcrypt.compare('123456', data.u_password, function (err, result) {
if (err) {
// Passwords don't match
message = 'Passwords dont match';
} else {
// Passwords match
message = 'Passwords match';
}
res.status(200).json({
message: message,
});
})
}
res.status(200).json({
message: "User Not found."
});
}
res.status(200).json({
message: "User Not found."
});
});
how to implement jwt verify token implement in node js.I already tried but its not showing error but its showing undefined.How to solve this issue.
auth.py
function jwtAccessAuthCheck(accessToken)
{
if(accessToken)
{
console.log("Sucess")
jwt.verify(accessToken,"secretkey",function(err){
if(err) {
console.log(typeof(err.message))
return err.message
}
else {
return "token"
}
});
}
else
{
return "Invalid token"
}
}
routes.py
//Get Data from Database
router.get('/', async (req, res,next) => {
(async function() {
try {
await client.connect();
console.log("Connected correctly to server");
const db = client.db('olc_prod_db');
const token_validation = validate_token.validate_token(req.headers.authorization)
console.log((token_validation))
const r = await db.collection('Ecommerce').find().toArray();
client.close();
res.send(r)
} catch(err) {
console.log(err.stack);
}
})();
});
const express = require('express');
const app = express();
const jwt = require('jsonwebtoken');
const bodyparser = require('body-parser');
const user = {username : "user",password : "pass"}
app.use(bodyparser.json());
const checkToken = function (req,res,next)
{
const header = req.headers['authorization'];
if(typeof header !== 'undefined')
{
const bearer = header.split(' ');
const token = bearer[1];
req.token=token;
next();
}
else
{
res.sendStatus(403);
}
}
app.post('/login',function (req,res)
{
const { body } = req;
const { username } = body;
const { password } = body;
if(username === user.username && password === user.password)
{
jwt.sign({user},'privatekey',{expiresIn : '1h'},function (err,token){
if(err)
{
console.log(err)
}
console.log(token);
res.end();
});
}
else
{
console.log('Error : Could not log in');
}
});
app.get('/data',checkToken,function(req,res)
{
jwt.verify(req.token,'privatekey',function (err,authorizedata)
{
if(err)
{
console.log('Error : Could not connect to the protected route');
res.sendStatus(403);
}
else
{
res.json({
message : 'Successful log in',
authorizedata
});
console.log('Success : Connected to protected route');
}
});
});
app.listen(3000,console.log("Server is running at 3000"));
This is how I have implemented JWT token
I want to call a stored procedure / function in postgresql from node/express. I am using Angular 5.
Installed packages:
express: 4.16.2,
pg: ^7.4.0
Other required packages are also installed
Below is the code of my API - I want to replace all queries with my stored procedure / function call
const express = require('express');
const router=express.Router();
const {Pool,Client} = require('pg');
const connectionString = 'postgresql://postgres:1#localhost:5432/dbAngular'
// const client = new Client({
// connectionString:connectionString
// })
router.get('/employees', (err, res, done) => {
const client = new Pool({
connectionString:connectionString
})
client.connect((err)=>{
if(err!=undefined)
{
console.log('connection not established message as follow '+err.message+'')
}
});
client.query('select * from getEmployees();', (err, result) => {
if (err) {
console.log(err.stack) ;
client.end();
} else {
client.end();
console.log(result.rows);
res.json(result.rows);
}
})
})
//SAVE
router.post('/employees', (req, res,next) => {
const client = new Pool({
connectionString:connectionString
})
console.log( req.body);
var employee=req.body;
const query = {
text: 'INSERT INTO employes(name) VALUES($1)',
values: [employee.name]
}
client.connect((err)=>{
if(err!=undefined)
{
console.log('connection not established '+err.message+'')
}
});
client.query(query, (err, result) => {
if (err) {
console.log('ERRROOORRRRR');
client.end();
console.log(err.stack)
} else {
console.log('SAVEEEEE');
client.end();
// console.log(res.rows[0])
res.json();
}
})
});
//delete
router.delete('/employees/:id', (req, res,next) => {
const client = new Pool({
connectionString:connectionString
});
console.log('id passed is ' + req.param.id);
client.query('DELETE FROM employes WHERE empid=($1)',[req.param.id], (err, result) => {
if (err) {
console.log('ERRROOORRRRR');
client.end();
console.log(err.stack)
} else {
console.log('SAVEEEEE');
client.end();
// console.log(res.rows[0])
res.json();
}
});
});
module.exports=router;