Nodejs rest api mysql - 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.

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);

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 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.

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

How to create a webservice using node.js to insert data into mysql?

I've a table in mysql that i need to be populated by calling a webservice.
The catch is, I would like to pass the data to be inserted into the database as parameters to the webservice.
How would I do this?
Using the MySQL module
http://npmjs.com/mysql
const mysql = require('mysql');
const express = require('express');
const app = express();
const connection = mysql.createConnection({
host: 'localhost',
user: 'me',
password: 'secret',
database: 'my_db'
});
connection.connect();
app.get('/', (req, res) => {
connection.query(`SELECT * FROM table`, (error, data) => {
if(error) {
console.log(error)
}else{
res.json(data)
}
});
});
app.post('/update/user/:id?', (req, res) => {
const id = req.params.id;
const username = req.body.username;
connection.query(`UPDATE MyGuests SET username='${username}' WHERE id=${id}`, (error, data) => {
if(error) {
console.log(error)
}else{
res.json(data)
}
});
});