nodeJsのexpress生成token
20695 ワード
nodeJsのexpress生成token
const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken'); // token
const cors = require('cors');
const mongoose = require('mongoose');
const app = express();
//
app.use(cors());
// application/x-www-form-urlencoded
// app.use(bodyParser.urlencoded({ extended: false }))
let jsonParser = bodyParser.json();
let urlencoded = bodyParser.urlencoded({ extended: false });
let connection = mongoose.createConnection('mongodb://localhost/mongodb',{useNewUrlParser: true});
//
let schema = new mongoose.Schema(
{
area:String,
prov:String,
city:String,
dealer:String,
name:String,
address:String,
phone:String,
code:String
}
);
let user = new mongoose.Schema(
{
name: String,
pass: String,
}
);
let Todo = connection.model('dealers', schema);
let Bm = connection.model('users', user);
app.post('/getdata',jsonParser,(req,res)=>{
let currData = req.body.currData;
let currentpage = req.body.currentpage;
let pageStart = 0, pageEnd = 0, len=0;
pageEnd = currData * currentpage;
pageStart = pageEnd - currData;
//
Todo.find().estimatedDocumentCount().then((data)=>{
len = data;
});
Todo.find().skip(pageStart).limit(currData).exec((err,data)=>{
if (err) throw err;
res.json({data:data,len:len})
});
});
//
app.post('/login',jsonParser,(req,res)=>{
let name = req.body.name;
let pass = req.body.pass;
Bm.find({name:name}).exec((err,data)=>{
if (err) throw err;
if (data.length!=0){
let content ={name:req.body.name}; // token
let secretOrPrivateKey="jwt";// key( )
let token = jwt.sign(content, secretOrPrivateKey, {
expiresIn: 60*60*1 // 1
});
if (pass != data[0].pass){
res.json({status:2,mess:' '});
return false;
}
res.json({status:1,mess:'ok',token:token,user_name:req.body.name})
} else {
res.json({status:401,mess:' '});
}
});
});
// token
app.post('/checkUser',jsonParser,(req,res)=>{
let token = req.get("Authorization"); // Authorization token
let secretOrPrivateKey="jwt"; // key( )
jwt.verify(token, secretOrPrivateKey, (err, decode)=> {
if (err) { // || token
res.send({'status':10010});
} else {
res.send({'status':10000});
}
})
});
app.listen(3000,()=>{
console.log('Server run 3000')
});