Nodejs & sequalize mysql query to the database happens only once - mysql

I have the following node code,i am trying to query the database based on a request,i use sequelize orm with mysql
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const axios = require("axios");
const models = require("./models");
const jsonParser = bodyParser.json();
app.post("/auth/change", jsonParser, (req, res) => {
let phoneNumber = req.body.phone;
let password = req.body.password;
console.log("phone number", phoneNumber);
models.users
.findOne({
where: {
phone: phoneNumber
}
})
.then(user => {
console.log(user.name);
}).catch(error => {
console.log(error);
});
});
app.listen(3000, () => {
console.log("Listening on port 3000");
});
I use react on the front end, and when i send a request with data for example
{phone:777,password:123} it works, but if i do a second request with same or different data it fails.What am i missing here!!?

you are not returning any data to the front side when it call the API , so the server will be waiting to return a response to the caller.
try to change your code to this :
models.users
.findOne({
where: {
phone: phoneNumber
}
})
.then(user => {
res.status(200).send('ok')
}).catch(error => {
res.status(400).send('not ok')
});

Related

error column cannot be null, trying to upload file into sql

i am still new in node js, and i am trying to make some backend with file upload/ image upload function that can be stored in sql, i am trying using multer but it cant read my file while testing in postman body. anybody can help me where i do wrong?
here is my controller
const { db } = require('./db');
const bodyParser = require('body-parser');
const getgambar = (req, res) => {
const sqlQuery = "SELECT * FROM gambar";
db.query(sqlQuery, (err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
console.log(result);
}
});
};
const addgambar = (req,res) => {
const idimg = req.body.idimg;
const gambar = req.file.gambar;
console.log()
const sqlQuery = "INSERT INTO image (idimg,gambar) VALUE (?,?)";
db.query(sqlQuery, [idimg,gambar], (err, result) => {
if (err) {
res.send({
message: "error",
err
})
} else {
res.send({
message: "YES"
})
}
});
};
module.exports = {
getgambar,
addgambar,
};
here is my route
const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const ctrl = require('./gambarctrl');
const storange = multer.diskStorage({
destination: './uploads',
filename: (req, file, cb) => {
return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`)
}
})
const upload = multer({
storange: storange
})
router.get('/image/display', ctrl.getgambar)
router.post('/image',upload.single('gambar'), ctrl.addgambar)
module.exports = router;
and here my index
const { db } = require('./db');
const express = require('express');
const bodyParser = require('body-parser')
const cors = require('cors');
const app = express();
const fileUpload = require('express-fileupload');
const gambarroute = require ('./gambarroute');
const multer = require('multer');
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(gambarroute);
app.listen(3000, () => {
console.log('on port 3000!');
});
i am still quite new in node js and i am still searching for tutorial, i appriciate for the help.
Two problems here...
Multer puts the single uploaded file into req.file so you should use
const gambar = req.file; // no `.gambar`
Assuming your DB column is a BLOB or BINARY type, you need to provide a Buffer.
Since you're storing the images within the DB, you don't need to use DiskStorage. Use MemoryStorage instead which provides a Buffer out-of-the-box
const upload = multer({
storage: multer.memoryStorage(), // watch your spelling
})
Then bind the .buffer property in your query.
db.query(sqlQuery, [idimg, gambar.buffer], (err, result) => {
// ...
});
To respond with the image from Express, use something like this
router.get("/image/display/:id", (req, res, next) => {
db.query(
"SELECT `gambar` FROM `image` WHERE `idimg` = ?",
[req.params.id],
(err, results) => {
if (err) {
return next(err);
}
if (!results.length) {
return res.sendStatus(404);
}
// set the appropriate content type
res.set("Content-Type", "image/jpg");
res.send(results[0].gambar);
}
);
});
and from the frontend...
<img src="http://localhost:3000/image/display/some-id" />

Could not get response when making POST request from Postman to Node.js (express), MySQL

I'm facing issues while making simple POST requests from NodeJS server running on localhost. Trying, to POST JSON format data from Postman to NodeJS with express storing data to MySQL. Using the MVC method of going through the Server -> Routes (will format the data) -> Controller (validation & strong to MySQL). Error handling was applied too. but no error showing on Terminal or Postman. I've might miss something on my routes I guess. Appreciate the help. Thanks in advance!
index.js
const express = require('express');
const authRoutes = require('./routes/auth');
const errorController = require('./controllers/error');
const app = express();
const PORT = 8080;
const ports = process.env.PORT || PORT;
// MIDDLEWEAR PARSE JSON DATA
app.use(express.json());
// HEADER ACCESS CONTROL, REQUEST, ROUTES
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Methods',
'GET, POST, PUT, DELETE, OPTIONS'
);
res.setHeader(
'Access-Control-Allow-Headers',
'Content-Type, Accept, X-Custom-Header, Authorization'
);
next();
});
// AUTH
app.use('/auth', authRoutes);
// PAGE NOT FOUND
app.use(errorController.get404);
// SERVER NOT RESPONDING
app.use(errorController.get500);
app.listen(PORT, () => {
console.log(`server started at port ${ports}`);
});
Routes/auth.js
const express = require('express');
const { body } = require('express-validator');
const router = express.Router();
const User = require('../models/user');
const authController = require('../controllers/auth');
router.post(
'/signup',
[
body('email')
.isEmail()
.withMessage('Please enter a valid email.')
.custom(async (email) => {
const user = await User.find(email);
if (user[0].length > 0) {
return Promise.reject('Email address already exist!');
}
})
.normalizeEmail(),
body('password').trim().isLength({ min: 7 }),
body('admin').not().isEmpty(),
],
authController.signup
);
module.exports = router;
controllers/auth.js
const { validationResult } = require('express-validator');
const bcrypt = require('bcryptjs');
const User = require('../models/user');
exports.signup = async (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return;
const email = req.body.email;
const password = req.body.password;
const admin = req.body.admin;
try {
const hashedPassword = await bcrypt.hash(password, 12);
const userDetails = {
email: email,
password: hashedPassword,
admin: admin,
};
const results = await User.save(userDetails);
return res.status(201).json({ message: 'User registered!' });
} catch (err) {
if (!err.statusCode) {
return err.statusCode = 500;
}
next(err);
}
};
error.js
// ERROR MIDDLEWARE
exports.get404 = (req, res, next) => {
const error = new Error('Not found');
error.status = 404;
next(error);
};
exports.get500 = (error, req, res, next) => {
res.status(error.status || 500);
res.json({
error: {
message: error.message,
},
});
};
Models/users.js
const db = require('../util/database');
module.exports = class User {
constructor(email, password, admin) { // TODO: , admin
this.email = email;
this.password = password;
this.admin = admin;
}
static find(email) {
return db.execute('SELECT * FROM users WHERE email = ?', [email]);
}
static save(user) {
return db.execute('INSERT INTO users (email, password) VALUES (?, ?, ?)', [
user.email,
user.password,
user.admin,
]);
}
};
Postman
POST -> http://localhost:8080/auth/signup
{
"email": "joe#gmail.com",
"password": "password",
"admin": "admin"
}

Getting empty {} from mysql table, on React and node.js

For some reason am getting empty object back from mysql table, the table is filled in with some vacation detail. And i want to display them with map in my react app.
On the client side am doing the request with useEffect state and axios.
useEffect(() => {
axios.get("http://localhost:3001/vacations")
.then((response) => {
let vacationsResponse = response.data;
dispatch({ type: ActionType.GetAllVacations, payload: vacationsResponse })
}).catch(err => {
console.log("Failed to get data" + err)
})
}, [dispatch])
this is the server side:
const vacationsControllers = require("./Controllers/vacationsControllers");
const cors = require("cors");
server.use(cors({ origin: "http://localhost:3000" }));
server.use("/users", usersController);
server.use("/vacations", vacationsControllers);
server.listen(3001, () => console.log("Listening on http://localhost:3001"));
this is the vacationsControllers folder:
router.get("/", async (request, response) => {
let vacationsData = request.body;
try {
await vacationsDao.getAllVacations(vacationsData);
response.json();
console.log(vacationsData) *get this empty in the node terminal*
} catch (e) {
console.error(e);
response.status(600).json();
}
});
module.exports = router;
The sql execute (the vacationDao folder):
let connection = require("./connection-wrapper");
async function getAllVacations(vacationsData) {
const sql = `SELECT * FROM current_deals`;
await connection.executeWithParameters(sql);
return vacationsData;
}
module.exports = {
getAllVacations,
};

nodejs mysql post method return an old unknow record

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.

Fastify and cloud functions

i try deployed a example in cloud functions for test and don't works, my code is:
`const functions = require('firebase-functions');
const Fastify = require('fastify')
const fastify = Fastify()
fastify.get("/",async (req, reply) =>{
reply.send({ hello: "world" })
})
fastify.listen(3000)
module.exports = { api: functions.https.onRequest(fastify) };`
Someone knows how deploy the server of fastify as express
this issue has been explained in Fastify some days ago.
You can check the full explanation here by maintainers
I'll post here the working solution:
const functions = require('firebase-functions')
const http = require('http')
const Fastify = require('fastify')
let handleRequest = null
const serverFactory = (handler, opts) => {
handleRequest = handler
return http.createServer()
}
const fastify = Fastify({serverFactory})
fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})
exports.app = functions.https.onRequest((req, res) => {
req = Object.assign({ip: ''}, {...req});
fastify.ready((err) => {
if (err) throw err
handleRequest(req, res)
})
})