In this blog, I will be explaining how to create a login API view with Node js and JWT. So let’s get started.
I this section, I am just summarizing what we did in the previous blog.
Initially we created a server and connected it to the MongoDB database with the mongoose instance. Then we created four folders named Models, Middleware, Controller, Routes.
index.js
const express = require('express')
const bodyparser = require('body-parser');
const mongoose = require('mongoose')
const router = require('./Routes/auth.route')
var app = express()
//Routes
app.use(bodyparser.json())
app.get('/', function(req,res){
res.send('Hello world')
})
app.use('/account/api',router)
//MongoDb connection
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true});
mongoose.connection.once('open',function(){
console.log('Database connected Successfully');
}).on('error',function(err){
console.log('Error', err);
})
//Server
app.listen('8000',function(req,res){
console.log('Serve is up and running at the port 8000')
})
After creating the server, we created a route file named auth.route
to handle all the authentication requests.
Routes/auth.route.js
const router = require('express').Router()
const signup = require('../Controller/auth.controller')
const {validateUser} = require('../Middleware/validation');
router.post('/signup',validateUser,signup.signup)
module.exports = router
Then we created a user Schema with attributes name, email, password.
Models/user.model.js
const mongoose = require('mongoose')
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
max: 200,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
min: 5
},
},{timestamps: true}
)
module.exports = mongoose.model('User',userSchema)
#jwt-auth #authentication #javascript #nodejs #expressjs