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

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" />

Related

How can I separate an API into diferent files? (routes) Node.js + MySQL

I'm new here. I wanted to know how can I "separate" mi app.js (API) into several files, mainly for the routes but also the connections too if it is posible. I tried several video tutorials but none of them worked, so here is my code (only file), I want the routes in a separated file (routes.js):
const mysql = require('mysql')
const bodyParser = require('body-parser')
const PORT = process.env.PORT || 3050
const app = express()
app.use(bodyParser.json())
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'shop'
})
app.get('/', (req, res) => {
res.send('Welcome to my API!')
})
//ROUTES!!!
app.get('/customers', (req, res) => {
const sql = 'SELECT * FROM customers'
connection.query(sql, (err, results) => {
if (err) throw err
if (results.length > 0) {
res.json(results)
} else {
res.send('No results!')
}
})
})
app.get('/customers/:id', (req, res) => {
const { id } = req.params
const sql = `SELECT * FROM customers WHERE id = ${id}`
connection.query(sql, (err, result) => {
if (err) throw err
if (result.length > 0) {
res.json(result)
} else {
res.send('No result!')
}
})
})
connection.connect(error => {
if (error) throw error
console.log('Database server running!')
})
app.listen(PORT, () => console.log(`Server running on ${PORT}`))
You can use express.Router object to define some routes in separe file. Then export the router object and do app.use('/api/some-sub-path', router)
You can read more about Router here https://expressjs.com/en/guide/routing.html
Also I advice you to read this article https://dev.to/santypk4/bulletproof-node-js-project-architecture-4epf
create n new file ApiRouter.js and add following code in it.
const express = require("express");
const router = express.Router();
router.get('/customers', (req, res) => {
const sql = 'SELECT * FROM customers'
connection.query(sql, (err, results) => {
if (err) throw err
if (results.length > 0) {
res.json(results)
} else {
res.send('No results!')
}
})
})
router.get('/customers/:id', (req, res) => {
const { id } = req.params
const sql = `SELECT * FROM customers WHERE id = ${id}`
connection.query(sql, (err, result) => {
if (err) throw err
if (result.length > 0) {
res.json(result)
} else {
res.send('No result!')
}
})
})
module.exports = router;
//now go to app.js file and add these line of codes below
app.use(bodyParser.json())
const route = require('./path/ApiRouter.js'); // require from file
app.use('/', route);
Create router in another file by:
const router = require('express').Router;
router.get();
And now in app.js use router as
app.use('/' , router);

Return node.js sql result to other file

I want to create a Website where I can display results from my mysql database.
I finished the website and the sql query, but I am stuck to return my SQL result.
Here is my code for my server with nodejs to display my pug file:
app.js
const express = require("express");
const app = express();
const path = require("path");
const router = express.Router();
var db=require("../node_js/db.js");
app.set("view engine","pug");
app.listen(3000, () => {
console.log("Application started and Listening on port 3000");
});
app.use(express.static(__dirname));
app.get("/", (req, res) => {
sql_result=query("SELECT * FROM test"); //here should i get my sql result
res.render("test",{title:"Card",details:sql_result});
});
My databse connection code:
db.js
function query(sql){
return new Promise(function(resolve,reject){
var connection=db;
connection.query(sql,function(err,rows,fields){
if(err){
return reject(err);
}
resolve(rows[randomRow(0,rows.length)]);
});
});
}
query("SELECT * FROM SONGS").then(function(rows){
console.log(rows);
}).catch((err)=>setImmediate(()=>{throw err;}));
I struggel to return 'rows' from query to my app.js file and use it in 'app.get("/").
in the first file you should require your other file to be able to use its functions.
and since it returns a promise you can use await to get the result.
app.js
const express = require("express");
const app = express();
const path = require("path");
const query = require("./db.js");
const router = express.Router();
var db=require("../node_js/db.js");
app.set("view engine","pug");
app.listen(3000, () => {
console.log("Application started and Listening on port 3000");
});
app.use(express.static(__dirname));
app.get("/", async (req, res) => {
let sql_result=await query("SELECT * FROM test"); //here should i get my sql result
res.render("test",{title:"Card",details:sql_result});
});
and the db.js
module.exports = function query(sql){
return new Promise(function(resolve,reject){
var connection=db;
connection.query(sql,function(err,rows,fields){
if(err){
return reject(err);
}
resolve(rows[randomRow(0,rows.length)]);
});
});
}

TypeError: req.getConnection is not a function

strong textI'm trying to create my first CRUD with Mysql, Node js and Express.js following a tutorial.
The problem is, in the video this code works, but in my visual give the error aboyt getConnection is not a function.
If anyones can help, I'll apreciate.
Server.js
const express = require("express");
const mysql = require("mysql");
const myconn = require("express-myconnection");
const routes = require("./routes");
const app = express();
const serverPort = process.env.PORT || 9000;
const dbOptions = {
host: "localhost",
user: "3306",
password: "123456",
database: "catalog",
};
//server running
app.listen(serverPort, () => {
console.log(`App listening at ${serverPort}`);
});
//routes
app.get("/", (req, res) => {
res.send("welcome to my API");
});
app.use("/phones", routes);
Routes.js
const express = require("express");
const routes = express.Router();
const myconn = require("express-myconnection");
routes.get("/", (req, res) => {
req.getConnection((err, conn) => {
if (err) return res.send(err);
conn.query("SELECT * FROM phones", (err, rows) => {
if (err) return res.send(err);
res.json(rows);
});
});
});
module.exports = routes;
UPDATE : solved.
IT WAS A POINT after catalog and I didn't write the port correctly!!!!!

Nodejs rest api mysql

I'm trying to display all members from MYSQL database with Node Js. But I get some errors. My database name is apibase and I have table members (id, name, email, phone) My code is below:
//routes.js file
const pool = require('../data/config');
const router = app => {
app.get('/', (request, response) => {
response.send({
message: 'Welcome to the Node.js Express REST API!'
});
});
// Display all users
app.get('/members', (request, response) => {
pool.query('SELECT * FROM members', (error, result) => {
if (error) throw error;
response.send(result);
});
});
// Display a single user by ID
app.get('/members/:id', (request, response) => {
const id = request.params.id;
pool.query('SELECT * FROM members WHERE id = ?', id, (error, result) => {
if (error) throw error;
response.send(result);
});
});
}
module.exports = router;
And my database.js file:
const mysql = require('mysql');
const config = {
host: 'localhost',
user: 'root',
password: '',
database: 'apibase',
};
const pool = mysql.createPool(config);
module.exports = pool;
And app.js file
const express = require('express');
const port = 8080;
const bodyParser = require('body-parser');
const routes = require('./routes/routes')
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true,
}));
routes(app);
const server = app.listen(port, (error) => {
if (error) return console.log(`Error: ${error}`);
console.log(`Server listening on port ${server.address().port}`);
});
I don't know what is the problem with this code, can somebody help me with this.

When I upload image through multer , I got image undefined error

I am using it with node and mysql with angular 5.
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');
const router = express.Router();
const multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './assets/images/')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
});
const fileFilter = (req, file, cb)=>{
if(file.mimetype === 'image/jpeg' || file.mimetype === 'image/png'){
cb(null, true);
}
else{
cb(null, false);
}
};
upload = multer({
storage: storage,
limits:{
filesize : 1024 * 1024 * 5
},
fileFilter : fileFilter
});
const app = express();
//DATABASE CONNECTION
const connection = mysql.createConnection({
host: 'localhost',
user:'root',
password: 'root',
database: 'inpblog',
port: 8889
});
// ALLOW CROSS ORIGIN
const corsOptions = {
origin: 'http://localhost:4200',
origin1: 'http://localhost:4202',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};
app.use(cors(corsOptions));
app.use('./assets/images', express.static(path.join(__dirname, 'dist', 'upload')));
const jsonParser = bodyParser.json();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
connection.connect(function(error){
if(!!error){
console.log("error - db not connected");
}
else{
console.log("connected");
}
});
Here i define the code to upload a image in mysql database. through postman its upload a image in destination folder with multer middleware but when i upload a image through ng form its showing error in console."image undefined" and submit the "c:/fakepath/image.jgg" in mysql.
Here is the API to insert the post
app.post('/insertPost', upload.single('txt_blog_image'), jsonParser, (req, res) => {
console.log("image: ", req.file); // working fine only with postman
//console.log("rBody: ", req.body.txt_blog_image); // working fine only with Angular
let blogFields = {
post_author : req.body.txt_blog_author,
post_image : req.body.txt_blog_image
};
let sql = 'INSERT INTO insdb SET ?';
let query = connection.query(sql, blogFields, (err,result)=> {
res.send('New Post added...');
});
});
// Get All Post
app.get('/getallposts', (req, res) => {
let sql = 'SELECT * FROM insdb';
let query = connection.query(sql, (err, results) => {
if(err) throw err;
console.log(results);
res.send(results);
});
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
app.listen(4202);
Try this way.
var path = require('path');
var multer = require('multer');
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './assets/images/')
},
filename: function(req, file, callback) {
console.log(file)
callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})
In your api :
app.post('/getallposts',upload.single("image") , function(req, res) {
let sql = 'SELECT * FROM insdb';
let query = connection.query(sql, (err, results) => {
if(err) throw err;
console.log(results);
res.send(results);
});
})
From Angular side :
let form = new FormData();
form.append('image' , file);
Then console in server side , req.files to check file is coming or not ?
For more information and example please see this link