harian untung99play.xyz

untung99play.xyz: Node JS MySQL CRUD Tutorial Example


Untung99 menawarkan beragam permainan yang menarik, termasuk slot online, poker, roulette, blackjack, dan taruhan olahraga langsung. Dengan koleksi permainan yang lengkap dan terus diperbarui, pemain memiliki banyak pilihan untuk menjaga kegembiraan mereka. Selain itu, Untung99 juga menyediakan bonus dan promosi menarik yang meningkatkan peluang kemenangan dan memberikan nilai tambah kepada pemain.

Berikut adalah artikel atau berita tentang Harian untung99play.xyz dengan judul untung99play.xyz: Node JS MySQL CRUD Tutorial Example yang telah tayang di untung99play.xyz terimakasih telah menyimak. Bila ada masukan atau komplain mengenai artikel berikut silahkan hubungi email kami di [email protected], Terimakasih.

Node js express crud with bootstrap & MySQL; In this example tutorial guide, you will learn how to make crud (create, update, read, delete) web applications in node js express js framework with MySQL database and bootstrap 4 libraries.

Node js express crud tutorial MySQL will create a crud customer management application. Which you can add customers, edit customers and also delete customers from the database using node js express with MySQL database with Bootstrap.

Crud operation in node js using express MySQL tutorial will help to create a crud operation application in node js express with MySQL database + bootstrap.

Node.JS Express CRUD with MySQL Tutorial Example

Let’s follow the following steps to create CRUD operation application in Node.JS express, bootstrap with MySQL:

  • Step 1 – Create Node JS App
  • Step 2 – Install Required Libraries
  • Step 3 – Connect to Node js Express Mysql CRUD App
  • Step 4 – Create Server.js File
  • Step 5 – Create CRUD Routes
  • Step 6 – Create views
  • Step 7 – Start Node Express js Crud + MySQL app

Step 1 – Create Node JS App

Execute the following command on terminal to create node js express app:

Use the below command and create your express project with name expressfirst

express --view=ejs expressfirst

After successfully created expressfirst folder in your system. Next follow the below commands and install node js in your project :

cd expressfirst

npm install

Step 2 – Install Required Libraries

Install flash, validator, session, override MySQL Libraries into your node js express crud + MySQL application by executing the following command on terminal:

 npm install express-flash --save
npm install express-session --save
npm install express-validator --save
npm install method-override --save
npm install mysql --save



express-flash

Flash is an extension of connect-flash with the ability to define a flash message and render it without redirecting the request.
In this node js mysql crud tutorial express flash is used to display a warning, error and information message

express-session

Express-session is used to made a session as like in PHP. In this node js mysql crud tutorial, session is needed as the express requirement of express-flash.

express-validator

Express validator is used to validate form data it is easy to use. express-validator highly effective and efficient way to accelerate the creation of applications.

method-override

NPM is used to run a DELETE and PUT method from an HTML form. In several web browsers only support GET and POST methods.

MySQL

Driver to connect node.js with MySQL

Step 3 – Connect to Node js Express MySQL CRUD App

Create one folder name lib and create a new file name db.js inside this folder. You need to connect node js to mysql using this file:

lib/db.js
 var mysql=require('mysql');
 var connection=mysql.createConnection({
   host:'localhost',
   user:'your username',
   password:'your password',
   database:'your database name'
 });
connection.connect(function(error){
   if(!!error){
     console.log(error);
   }else{
     console.log('Connected!:)');
   }
 });  
module.exports = connection; 

Step 4 – Create Server.js File

Visit your app root directory and create a new file name server.js And add the following code into it:

 var createError = require('http-errors');
 var express = require('express');
 var path = require('path');
 var cookieParser = require('cookie-parser');
 var logger = require('morgan');
 var expressValidator = require('express-validator');
 var flash = require('express-flash');
 var session = require('express-session');
 var bodyParser = require('body-parser');

 var mysql = require('mysql');
 var connection  = require('./lib/db');

 var indexRouter = require('./routes/index');
 var usersRouter = require('./routes/users');
 var customersRouter = require('./routes/customers');

 var app = express();

// view engine setup
 app.set('views', path.join(__dirname, 'views'));
 app.set('view engine', 'ejs');

 app.use(logger('dev'));
 app.use(bodyParser.json());
 app.use(bodyParser.urlencoded({ extended: true }));
 app.use(cookieParser());
 app.use(express.static(path.join(__dirname, 'public')));

 app.use(session({ 
     secret: '123456cat',
     resave: false,
     saveUninitialized: true,
     cookie: { maxAge: 60000 }
 }))

 app.use(flash());
 app.use(expressValidator());

 app.use('/', indexRouter);
 app.use('/users', usersRouter);
 app.use('/customers', customersRouter);

 // catch 404 and forward to error handler
 app.use(function(req, res, next) {
   next(createError(404));
 });

 // error handler
 app.use(function(err, req, res, next)  500);
   res.render('error');
 );
// port must be set to 3000 because incoming http requests are routed from port 80 to port 8080
app.listen(3000, function () {
    console.log('Node app is running on port 3000');
});
 module.exports = app;

Step 5 – Create CRUD Routes

Create crud route file name customers.js; so visit inside routes folder and create this file. Then add the following code into it:

var express = require('express');
var router = express.Router();
var connection  = require('../lib/db');
/* GET home page. */
router.get('/', function(req, res, next) {
connection.query('SELECT * FROM customers ORDER BY id desc',function(err,rows)     {
if(err){
req.flash('error', err); 
res.render('customers',{page_title:"Customers - Node.js",data:''});   
}else{
res.render('customers',{page_title:"Customers - Node.js",data:rows});
}
});
});
// SHOW ADD USER FORM
router.get('/add', function(req, res, next){    
// render to views/user/add.ejs
res.render('customers/add', {
title: 'Add New Customers',
name: '',
email: ''        
})
})
// ADD NEW USER POST ACTION
router.post('/add', function(req, res, next){    
req.assert('name', 'Name is required').notEmpty()           //Validate name
req.assert('email', 'A valid email is required').isEmail()  //Validate email
var errors = req.validationErrors()
if( !errors ) {   //No errors were found.  Passed Validation!
var user = {
name: req.sanitize('name').escape().trim(),
email: req.sanitize('email').escape().trim()
}
connection.query('INSERT INTO customers SET ?', user, function(err, result) {
//if(err) throw err
if (err) {
req.flash('error', err)
// render to views/user/add.ejs
res.render('customers/add', {
title: 'Add New Customer',
name: user.name,
email: user.email                    
})
} else {                
req.flash('success', 'Data added successfully!');
res.redirect('/customers');
}
})
}
else {   //Display errors to user
var error_msg = ''
errors.forEach(function(error) {
error_msg += error.msg + '
' }) req.flash('error', error_msg) /** * Using req.body.name * because req.param('name') is deprecated */ res.render('customers/add', { title: 'Add New Customer', name: req.body.name, email: req.body.email }) } }) // SHOW EDIT USER FORM router.get('/edit/(:id)', function(req, res, next){ connection.query('SELECT * FROM customers WHERE id = ' + req.params.id, function(err, rows, fields) { if(err) throw err // if user not found if (rows.length <=>' }) req.flash('error', error_msg) /** * Using req.body.name * because req.param('name') is deprecated */ res.render('customers/edit', { title: 'Edit Customer', id: req.params.id, name: req.body.name, email: req.body.email }) } }) // DELETE USER router.get('/delete/(:id)', function(req, res, next) { var user = { id: req.params.id } connection.query('DELETE FROM customers WHERE id = ' + req.params.id, user, function(err, result) { //if(err) throw err if (err) { req.flash('error', err) // redirect to users list page res.redirect('/customers') } else { req.flash('success', 'Customer deleted successfully! id = ' + req.params.id) // redirect to users list page res.redirect('/customers') } }) }) module.exports = router;

Step 6 – Create views

Now, you need to create one folder name customers inside the views folder. And then need to create three views file name add.ejs, edit.ejs and index.ejs.

Create first file index.ejs

Index.ejs file, you will display the list of customers.

Create second file name add.ejs

Add.ejs file, you will create form for sending to data in database.

Create third file name edit.ejs

Next, create file name edit.ejs, you will edit data in this form.

Step 7 – Start Node Express js Crud + MySQL app

run the below command

npm start

after run this command open your browser and hit

http://127.0.0.1:3000/customers

Node js express crud tutorial mysql will looks like:

Conclusion

Node js + express crud with MySQL tutorial; you have learned how to build crud (create, read, update, delete) application with mysql database in node express js.

Recommended Node Js Tutorials