Node - js 设置 cookie和token

基于express框架学习
http://www.expressjs.com.cn/

链接MySQL数据库

在数据建立完整后,在node中操作链接

  /**数据库**/
 var Client = require('mysql').createConnection({
 host: '127.0.0.1',
   user: 'root',
   password: '*******',
   database: '********',
   charset: 'UTF8',
 });
查询数据库
 var querStr = `select * from 表名 where 条件`;
   Client.query(
       querStr, function selectCb(err, results, fields) {
    if (err) {
      throw err;
    }
  });
后台登录cookie
  1. 设置cookie
    var serialize = function(name, val, opt) {
    var pairs = [name + '=' + val];
    opt = opt || {};
    if (opt.maxAge) pairs.push('Max-Age=' + opt.maxAge);
    if (opt.domain) pairs.push('Domain=' + opt.domain);
    if (opt.path) pairs.push('Path=' + opt.path);
    if (opt.expires) pairs.push('Expires=' + opt.exppires.toUTCString());
    if (opt.httpOnly) pairs.push('HttpOnly');
    if (opt.secure) pairs.push('Secure');
    return pairs.join(';');
    };

  2. 登录匹配成功后设置cookie
    res.setHeader('Set-Cookie', serialize('isVisit', '1'));

3.代码

   var serialize = function(name, val, opt) {
   var pairs = [name + '=' + val];
   opt = opt || {};
   if (opt.maxAge) pairs.push('Max-Age=' + opt.maxAge);
   if (opt.domain) pairs.push('Domain=' + opt.domain);
   if (opt.path) pairs.push('Path=' + opt.path);
   if (opt.expires) pairs.push('Expires=' + opt.exppires.toUTCString());
   if (opt.httpOnly) pairs.push('HttpOnly');
   if (opt.secure) pairs.push('Secure');
   return pairs.join(';');
 };
   router.post('/login', function(req, res) {
   var username = req.body.username;
   var password = req.body.password;
   var querStr = `select * from adminuser where username = '${username}' and password ='${password}'`;
   Client.query(
  querStr, function selectCb(err, results, fields) {
    if (err) {
      data = {state: 0, results: ''};
      throw err;
    }
    if (results.length === 0) {
      data = {state: 0, results: ''};
    } else {
      data = {state: 1, results: "登录成功"};
    }
    res.setHeader('Set-Cookie', serialize('isVisit', '1'));
    res.json(data);
  });
 });

4.下次请求时验证

if (!req.cookies.isVisit) {
console.log('用户未授权');
res.json(unlogin);
} else {
}
移动端设置token

1.npm导入

npm install jwt-simple

2.设置

var express = require('express');
var jwt = require('jwt-simple');
var app = express();
app.set('jwtTokenSecret', 'YOUR_SECRET_STRING');

3.匹配成功设置token

/**设置移动端登录连续七天过后过期**/
var expires = moment().add(7, 'days').valueOf();
var token = jwt.encode({
    iss: results.id,
    exp: expires,
}, app.get('jwtTokenSecret'));

4.全部代码

/**用户登录接口**/
router.post('/mobile/login', function(req, res) {
var username = req.body.username;
var password = req.body.password;
var querStr = `select * from “表名” where username = '${username}' and password = '${password}'`;
Client.query(
  querStr, function selectCb(err, results, fields) {
    if (err) {
      data = {state: 0, results: ''};
      throw err;
    }
    if (results.length === 0) {
      data = {state: 0, results: ''};
    } else {
      /**设置移动端登录连续七天过后过期**/
      var expires = moment().add(7, 'days').valueOf();
      var token = jwt.encode({
        iss: results.id,
        exp: expires,
      }, app.get('jwtTokenSecret'));
      data = {state: 1, results: results, token: token};
    }
    res.json(data);
  });
 });

5.下次请求验证

var decoded = jwt.decode(token, app.get('jwtTokenSecret'));
  if (decoded.exp <= Date.now()) {
    console.log('授权错误');
    res.json(unlogin);
  } else {
 }
1.png
2.png

推荐阅读更多精彩内容