Tutorial NodeJS
Tutorial NodeJS
Tutorial NodeJS
1
return res.status(400).send('No files were uploaded.');
<form action="" method="POST" enctype="multipart/form-data"> }
<input type="file" name="target_file" required>
<input type="submit" value="Upload"> // Accessing the file by the <input> File name="target_file"
</form> let targetFile = req.files.target_file;
});
2
// Checking File Size (Max Size - 1MB)
if(targetFile.size > 1048576){ let targetFile = req.files.target_file;
let extName = path.extname(targetFile.name);
// Deleting Temporary File let baseName = path.basename(targetFile.name, extName);
fs.unlinkSync(targetFile.tempFilePath); let uploadDir = path.join(__dirname, 'uploads', targetFile.name);
return res.status(413).send("File is too Large");
} if(targetFile.size > 1048576){
fs.unlinkSync(targetFile.tempFilePath);
targetFile.mv(path.join(__dirname, 'uploads', targetFile.name), (err) => { return res.status(413).send("File is too Large");
if (err) }
return res.status(500).send(err);
res.send('File uploaded!'); // Renaming the file
}); let num = 1;
while(fs.existsSync(uploadDir)){
}); uploadDir = path.join(__dirname, 'uploads', baseName + '-' + num + extName);
num++;
app.listen(3000, () => console.log('Your app listening on port 3000')); }
3
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
CRUD RESTful API using Node.js
}); (Express.js) and MySQL Database
July 22, 2020Node JS Projects
app.post('/', (req, res) => {
Node JS (Express JS, MySQL) CRUD RESTful API
if (!req.files || Object.keys(req.files).length === 0) { Here we are going to create a simple CRUD RESTful API
return res.status(400).send('No files were uploaded.'); using Node.js with Express.js Framework and MySQL Database.
} And through this RESTful API, we will be inserting user name and email address
into the MySQL Database (Instead of the MySQL DB, You can also use the
let targetFile = req.files.target_file; MariaDB.).
let extName = path.extname(targetFile.name); The purpose of this tutorial is to give an idea of creating RESTful APIs using Node JS.
let baseName = path.basename(targetFile.name, extName);
let uploadDir = path.join(__dirname, 'uploads', targetFile.name);
Follow the below steps to create this Node.JS CRUD RESTful API
1) Database Setup
let imgList = ['.png','.jpg','.jpeg','.gif'];
First of all, we have to create our database and database table where we will store
// Checking the file type
user information. In the following, the database information is given –
if(!imgList.includes(extName)){
Database Name – node_restful_api
fs.unlinkSync(targetFile.tempFilePath);
return res.status(422).send("Invalid Image"); Table name – users
} Now open your MySQL DB or MariaDB and create a new database
called node_restful_api. And after creating this DB, use the following SQL code to
if(targetFile.size > 1048576){ create the `users` table and the structure of this table –
fs.unlinkSync(targetFile.tempFilePath); SQL Code for `users` table
return res.status(413).send("File is too Large"); CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
} `name` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
let num = 1; PRIMARY KEY (`id`),
while(fs.existsSync(uploadDir)){ UNIQUE KEY `email` (`email`)
uploadDir = path.join(__dirname, 'uploads', baseName + '-' + num + extName); ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
num++;
} 2) Node JS env setup & installing node packages
After completing the Database configuration, create a new folder on your Desktop,
targetFile.mv(uploadDir, (err) => { and name it whatever you want. Here I named it node-rest-api.
if (err) Now go inside the node-rest-api folder and initialize the NPM with the help of
return res.status(500).send(err); the npm init command.
res.send('File uploaded!'); After that, you have to install some Node Packages to create this application in my
}); way. Use the following command to install those packages at once –
npm install --save express express-validator mysql2
}); After installing the above node packages my package.json file looks like the
app.listen(3000, () => console.log('Your app listening on port 3000')); following –
package.json
{
"name": "node-restful-api",
"version": "1.0.0",
4
"description": "",
"main": "index.js", After making the Database connection, now we will create the validator.js for
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1" validating the request data.
}, To validating the requested data we will use the express-validator package. So if
"author": "Chandan Tudu", don’t know how to use this package to validate the requested data, then check out
"license": "ISC", the following tutorial –
"dependencies": { Validate form data in Node JS (Express JS) with express-validator package
"express": "^4.17.1",
validator.js
"express-validator": "^6.6.0",
const db_connection = require("./db-connection").promise();
"mysql2": "^2.1.0"
const { body, param, validationResult } = require("express-validator");
}
}
module.exports = {
// User name and email Validation
3) Creating files & folders userInfo: [
Now time to create the application files & folders. But, before going further, let’s body("name", "The name must be of minimum 3 characters length")
have a look at the node-rest-api folder structure. See the below image – .optional()
.isLength({ min: 3 })
.trim()
.unescape()
.escape(),
}; if (update.affectedRows === 1) {
return res.json({
message: "The User has been successfully updated.",
// FETCHING SINGLE USER });
exports.getUserByID = async (req, res, next) => { }
7
const allRoutes = require("./routes");
// Handling Errors
app.use((err, req, res, next) => {
// console.log(err);
err.statusCode = err.statusCode || 500;
err.message = err.message || "Internal Server Error";
res.status(err.statusCode).json({
message: err.message,
});
});
GET - http://localhost:3000/get-all-users
GET - http://localhost:3000/get-user/{user_id}
PATCH - http://localhost:3000/update-user/{user_id}
DELETE - http://localhost:3000/delete-user/{user_id}
Inserting User
POST - http://localhost:3000/insert-user
8
Fetching all users Result after updating the user
GET - http://localhost:3000/get-user/{user_id}
DELETE - http://localhost:3000/delete-user/{user_id}
Fetching single user by ID
PATCH - http://localhost:3000/update-user/{user_id}
Deleting User 1
Updating User
9
Result after deleting the user
10
Node JS Form Handling: GET, POST Requests, Form Data Validation Params Example (index.js)
December 20, 2020Node JS const express = require('express');
const app = express();
In this Node JS Form Handling tutorial, you will learn how to get Form data
through the GET and POST requests, and how to validate the form data (Form app.get('/test/:id', (req,res) => {
console.log(`The ID is - ${req.params.id}`);
Validation).
res.send('Check the console');
Content of Form Handling in Node.js });
GET Request
URL Params app.listen(3000, () => console.log('Your app listening on port 3000'));
POST Request
JSON Payload http://localhost:3000/test/21
Form Validation
The ID is - 21
✍ Before getting started
In this tutorial, we will use Express.js framework. So frist, create a new folder on
POST Request in Node JS
your desktop called node-form-handling, the name is completely up to you, basically,
If you want to get the data requested from the POST method, you have to use
this is our app folder.
the express.urlencoded() middleware.
After that, go inside the app folder and initialize the npm, and then you have to
After applying the middleware, now you can access the post data using req.body
install the express.js (use the following the command to install it)–
npm i express POST Example (index.js)
const express = require('express');
const app = express();
GET Request in Node JS
You can access GET requested data using – req.query // Applying the middleware
GET Example (index.js) app.use(express.urlencoded({extended:false}));
const express = require('express');
const app = express(); app.get('/', (req, res) => {
// HTML Form (POST Method)
app.get('/', (req, res) => { res.send(`<form action="/test" method="POST">
// HTML Form <label>Username</label><br>
res.send(`<form action="/test" method="GET"> <input type="text" name="username" placeholder="Enter Username"><br>
<label>Username</label><br> <label>Password</label><br>
<input type="text" name="username" placeholder="Enter Username"><br> <input type="password" name="pass" placeholder="Enter Password"><br><br>
<label>Password</label><br> <input type="submit">
<input type="password" name="pass" placeholder="Enter Password"><br><br> </form>`);
<input type="submit"> });
</form>`);
}); app.post('/test', (req,res) => {
console.log(req.body);
app.get('/test', (req,res) => { res.send('Check the console');
//Displaying the GET data in console });
console.log(req.query);
res.send('Check the console'); app.listen(3000, () => console.log('Your app listening on port 3000'));
});
JSON payload in Node JS
app.listen(3000, () => console.log('Your app listening on port 3000')); But, if you want to request the data through the REST API with JSON payload,
then you have to apply the express.json() middleware.
Parse URL params value in Node JS JSON Payload (index.js)
You can parse the URL params data using – req.params const express = require('express');
11
const app = express();
//<input type="text" name="user_email">
app.use(express.json()); body('user_email').isEmail(),
13
<input type="password" name="pass" placeholder="Enter password"><br>
<label>Confirmation Password</label><br>
<input type="password" name="confirmation_pass" placeholder="Confirmation
Password"><br><br>
<input type="submit">
</form>`);
});
app.post('/test',
[
body('pass', 'Password must be between 5 and 10 characters').isLength({min:5,max:10}),
How to Update Data of MySQL
body('confirmation_pass').custom((value, {req}) => {
if (value !== req.body.pass) {
throw new Error('Password and confirm password does not match');
Database Using Node JS
} October 26, 2019 Node JS
return true; Here you will learn how to Update Data of MySQL Database Using Node JS. To
}), Update Data of MySQL Database, we will use the mysql2 module.
], But, before going further, I suggest you first check out this –
(req,res) => { Create MySQL Database Connection with Node JS
How to Query a MySQL Database using Node JS
const validation_result = validationResult(req); Insert Data Into MySQL Database Using Node JS
Fetch (Select) Data From MySQL Database Using Node JS
if(validation_result.isEmpty()){
14
});
db_connection.promise()
.execute("UPDATE `users` SET `name`=? WHERE `id`=?",[_new_name, 1])
.then(([result]) => {
//console.log(result);
if(result.affectedRows === 1){
How to Delete Data From MySQL
}
console.log("User Successfully Updated.");
Database Using Node JS
}).catch(err => { October 26, 2019Node JS
console.log(err);
}); Here you will learn how to Delete Data from MySQL Database Using Node JS. To
Delete Data from MySQL Database, we will use the mysql2 module.
Full Code of Update Data But, before going further, I suggest you first check out this –
Full code Create MySQL Database Connection with Node JS
How to Query a MySQL Database using Node JS
const mysql = require('mysql2');
const db_connection = mysql.createPool({ Insert Data Into MySQL Database Using Node JS
host: 'localhost', Fetch (Select) Data From MySQL Database Using Node JS
user: 'root', Update Data of MySQL Database Using Node JS
database: 'test',
password:'your_db_password'
Database Configuration
});
Database Name – test
let _new_name = "Adam Smith"; Table Name – users
So first, Strat your MySQL Server and create a Database called test, and then inside
db_connection.promise() the test database create a table called users.
.execute("UPDATE `users` SET `name`=? WHERE `id`=?",[_new_name, 1])
Use the following SQL Code to create users table and the structure of the users table.
.then(([result]) => {
//console.log(result);
if(result.affectedRows === 1){ CREATE TABLE `users` (
console.log("User Successfully Updated."); `id` int(11) NOT NULL AUTO_INCREMENT,
} `name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
}).catch(err => { `age` int(11) NOT NULL,
console.log(err); `email` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
}); PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4
COLLATE=utf8mb4_unicode_ci;
Database Connection
db_connection.promise()
.execute("DELETE FROM `users` WHERE `id`=?",[1])
.then(([result]) => {
if(result.affectedRows === 1){
console.log("User Successfully Deleted.");
}
}).catch(err => {
console.log(err);
});
16