当前位置:网站首页>Generating access keys using JSON webtoken
Generating access keys using JSON webtoken
2022-04-23 17:15:00 【MiMenge】
Back end
const {
response } = require('express');
const express = require('express');
const fs = require('fs');
const jwt = require('jsonwebtoken');
const app = express();
app.use(express.urlencoded({
extended: false }));
app.use(express.json());
app.use('*', (request, response, next) => {
// // Gets the of the header token
// let token = request.headers.authorization;
// // check token
// jwt.verify(token, 'MiMenge001018', (err, data) => {
// if (err && err.message === 'invalid token') {
// return response.json({ message: ' Invalid token', code: 0 });
// } else if (err && err.message === 'jwt expired') {
// return response.json({ message: ' invalid token', code: 0 })
// }
// });
next();
});
app.get('/', (request, response) => {
fs.readFile('./public/index.html', (err, data) => {
if (err) {
response.json({
message: ' Page resource not found ', code: 0 });
} else {
response.send(data.toString());
}
});
});
app.get('/demo', (request, response) => {
fs.readFile('./public/demo.html', (err, data) => {
if (err) {
response.json({
message: ' Page resource not found ', code: 0 });
} else {
response.send(data.toString());
}
});
});
app.post('/login', (request, response) => {
let {
uname, password } = request.body;
if (uname === 'Tom' && password === '1234') {
let token = jwt.sign({
uname: 'MiMenge',
iSRoot: true
}, 'MiMenge001018', {
expiresIn: 60
});
response.json({
message: 'OK', code: 0, token, });
}
});
app.post('/data', (request, response) => {
let token = request.headers.authorization;
jwt.verify(token, 'MiMenge001018', (err, data) => {
if (err) {
if (err.message === 'invalid token') {
return response.json({
message: ' Invalid token', code: 0 });
} else {
return response.json({
message: ' invalid token', code: 0 })
}
} else {
response.json({
message: ' success ', code: 1 });
}
})
});
app.listen(3300, err => {
if (err) {
console.error(err);
return;
}
console.log('success');
});
front end
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<a href=""> obtain </a>
<script> let a = document.querySelector('a'); a.addEventListener('click', (e) => {
e.preventDefault(); let token = localStorage.getItem('token'); let headers = new Headers({
'Authorization': token }); fetch('http://localhost:3300/data', {
method: 'post', headers }).then(data => data.text()).then(value => console.log(value)); // // Create request object // let xml = new XMLHttpRequest(); // // Initialization request // xml.open('post', 'http://localhost:3300/data', true); // // Set request header // xml.setRequestHeader('Content-Type', 'application/json;charset=utf8'); // // console.log(JSON.stringify(new AddO(uname, pwd))); // // Send request data // xml.send(JSON.stringify({ 'token': token })); // // Set request delay // xml.timeout = 3000; // xml.addEventListener('timeout', () => {
// xml.abort(); // }); // xml.addEventListener('error', () => {
// alert(' Wrong request ') // }); // xml.addEventListener('readystatechange', () => {
// if (xml.readyState === 4) {
// if (xml.status >= 200 && xml.status < 300 || xml.status === 304) {
// console.log(xml.responseText); // // console.log(xml.responseURL); // // console.log(xml.status); // // console.log(xml.statusText); // } // } // }); }); </script>
</body>
</html>
版权声明
本文为[MiMenge]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230553027505.html
边栏推荐
- Solution of Navicat connecting Oracle library is not loaded
- Get the column name list of the table quickly in Oracle
- Lock lock
- Decimal format decimal / datetime conversion processing
- XTask与Kotlin Coroutine的使用对比
- Generate random numbers with high quality and Gaussian distribution
- Using quartz under. Net core - calendar of [6] jobs and triggers
- Oninput one function to control multiple oninputs (take the contents of this input box as parameters) [very practical, very practical]
- Document operation II (5000 word summary)
- Variable length parameter__ VA_ ARGS__ Macro definitions for and logging
猜你喜欢

Perception of linear algebra 2

Simulation of infrared wireless communication based on 51 single chip microcomputer

Milvus 2.0 détails du système d'assurance de la qualité

Go language, array, string, slice

【WPF绑定3】 ListView基础绑定和数据模板绑定

JS, entries(), keys(), values(), some(), object Assign() traversal array usage

Devexpress GridView add select all columns

Clickhouse table engine

RPC核心概念理解

XTask与Kotlin Coroutine的使用对比
随机推荐
Solution of Navicat connecting Oracle library is not loaded
Conversion between hexadecimal numbers
JS to find the character that appears three times in the string
Detailed explanation of the penetration of network security in the shooting range
Low code development platform sorting
Your brain expands and shrinks over time — these charts show how
Scope and scope chain in JS
Freecodecamp ---- budget & category exercise
Linux MySQL data timing dump
Error in v-on handler: "typeerror: cannot read property 'resetfields' of undefined"
Use of Shell sort command
手写事件发布订阅框架
Using quartz under. Net core - [1] quick start
PHP efficiently reads large files and processes data
Some problems encountered in recent programming 2021 / 9 / 8
websocket
Input file upload
Generation of barcode and QR code
. net cross platform principle (Part I)
Summary of common websites