Node - js 設(shè)置 cookie和token

基于express框架學習
http://www.expressjs.com.cn/

鏈接MySQL數(shù)據(jù)庫

在數(shù)據(jù)建立完整后,在node中操作鏈接

  /**數(shù)據(jù)庫**/
 var Client = require('mysql').createConnection({
 host: '127.0.0.1',
   user: 'root',
   password: '*******',
   database: '********',
   charset: 'UTF8',
 });
查詢數(shù)據(jù)庫
 var querStr = `select * from 表名 where 條件`;
   Client.query(
       querStr, function selectCb(err, results, fields) {
    if (err) {
      throw err;
    }
  });
后臺登錄cookie
  1. 設(shè)置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. 登錄匹配成功后設(shè)置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('用戶未授權(quán)');
res.json(unlogin);
} else {
}
移動端設(shè)置token

1.npm導入

npm install jwt-simple

2.設(shè)置

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

3.匹配成功設(shè)置token

/**設(shè)置移動端登錄連續(xù)七天過后過期**/
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 {
      /**設(shè)置移動端登錄連續(xù)七天過后過期**/
      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('授權(quán)錯誤');
    res.json(unlogin);
  } else {
 }
1.png
2.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容