// ***** app2.js ***
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true}))
app.use(express.static('public')) // no install needed, it is a build-in middleware
var path = require('path') // install needed
const jsonWebToken = require('jsonwebtoken') // npm install required
const myJWTSecretKey = 'jd-secret-key' // This is not passed around web traffic
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/public/html/home.html'))
})
app.get('/public',
(req, res) => {
res.send('hello from public')
}
)
app.listen(3000, () => {
console.log('Server is running at: 3000, 930-622')
})
client-side | server-side | |
---|---|---|
home page | A user click login button | |
app2.js login.get route | It responds with the login page | |
login page | A user enter username and password, click the login button in this page | |
app2.js login post route | It verifies the user and issue a token, return the token. | |
login page, ajax callback function | It extracts the token and save it in sessionStorage. |
after login, you can ...
the msg is
test note: the data in db has only one user username: wiwi password: iwiwclient-side | server-side | |
---|---|---|
home.html | click the button, requesting get route for private | |
app2.js app.get('/private')(...){} | send private.html to the client | |
private.html | click the button for private data | |
private.html | It gets the token from sessionStorage. It posts the token, makes a ajax web request |
|
app2.js app.post('/private') | It gets the token from the request body. It call a function, using the token as function argument to verify the token |
|
app2.js function verifyToken | argument for input: token jsonWebToken.verify(token, myJWSecretkey) to verify the token If a valid token, the function return true. If a invalid token, the function return false. |
|
app2.js app2.js app.post('/private') after the function call | If the function returns false, return a error message. If the function returns true, return the required application data. |
|
private.html ajax callback | $.ajax({... success: function(response){...} get the message from the response render the message - data or error. |
auth is needed to access this page
data:
// app2.js ---------------------------------------- app.get('/private', (req, res) => { res.sendFile(path.join(__dirname + '/public/html/private.html')) } ) app.post('/private', (req, res) => { console.log('enter private') // get the token const token = req.body.token console.log('test 11:40, in private, token = ' + token) // call a function to verify var result = verifyToken(token) var msg if (result === false){ msg = 'no token or invalid token, please login again' } else { msg = 'This is the data from private route' } // return data res.json({ message: msg }) })