基于express框架实现小程序登录

  • • 发表于 7年前
  • • 作者 凉皮
  • • 3593 人浏览
  • • 2 条评论
  • • 最后编辑时间 7年前
  • • 来自 [问 答]

原创声明:本文为作者原创,未经允许不得转载,经授权转载需注明作者和出处

如何拿到token返回给前端

服务器代码如下

var express = require('express');
var router = express.Router();
var request = require('request');
var redis = require('redis');
var util = require('util');
var moment = require('moment');
var mongoose = require('mongoose');
var User = require('../models/User');
/* GET home page. */

router.get('/', function (req, res, next) {
  res.render('index', {
    title: 'Express'
  });
});

//小程序配置
var config = {
  'AppID': '我的appid',
  'AppSecret': '我的appsecret'
};

//生成token
function createToken() {
  const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  const length = chars.length;
  let str = "";
  for (let i = 0; i < length; i++) {
    str += chars.substr(Math.round(Math.random() * length), 1);
  }
  return str;
};

/**
 * 登录接口
 * 接收前端传入的用户基本信息
 * nickname:用户名
 * head_img:用户头像
 * code:用户凭证
 * openID:用户登录唯一凭证
 */
router.get('/login', function (req, res, next) {
  var nickname = req.query.nickName;
  var head_img = req.query.head_img;
  var code = req.query.code;
  var param = {}
  param.nickname = nickname;
  param.head_img = head_img;
  param.code = code;
  param.creatAt = moment().format('YYYY-MM-DD HH:mm:ss');
  request.get({
    url: 'https://api.weixin.qq.com/sns/jscode2session',
    json: true,
    qs: {
      grant_type: 'authorization_code',
      appid: config.AppID,
      secret: config.AppSecret,
      js_code: code
    }
  }, function (err, res, data) {
    if (res.statusCode === 200) {
      User.findOne({
        openid: data.openid
      }).then(function (info) {
        if (info) {
          console.info('用户已经存在');
          console.info(info.token)
          return res.send(token);
        } else {
          var user = new User({
            openid: data.openid,
            nickName: param.nickname,
            avatarUrl: param.head_img,
            creatAt: param.creatAt,
            token: createToken()
          })
          return user.save();
        }
      })
    } else {
      console.info('[error]', err)
      res.json(err);
    }
  })
})

module.exports = router;

小程序的逻辑如下

App({
  onLaunch: function () {
    //调用api从本地缓存中获取token
    var token = wx.getStorageSync('token') || '';
    console.info('从本地缓存中获取token数据')
    if(token == null || token == ''){
      var that = this;
      console.info('token is null');
      that.login();
    }else{
      console.info('token is not null');
      // that.queryUserInfo(token);
    }
  },
  //登录接口,登陆成功后设置全局用户信息
  login:function(){
    //获取授权码code
    wx.login({
      success: function (res) {
        console.info('授权码code')
        var code = res.code;
        console.info(code);
        if (code) {
          //获取用户信息接口
          wx.getUserInfo({
            success: function (res) {
              var userInfo = res.userInfo;
              // this.globalData.userInfo = userInfo;
              console.info(userInfo)
              var nickName = userInfo.nickName;
              var avatarUrl = userInfo.avatarUrl;
              //调用后端登录接口
              wx.request({
                url: 'http://127.0.0.1:3000/login',
                data: {
                  code: code,
                  nickName: nickName,
                  head_img: avatarUrl
                },
                success:function(res){
                  console.info('请求成功')
                  console.info(res);
                }
              })
            }
          })
        } else {
          console.info('获取用户登录凭证失败');
        }
      }
    })
  },
  globalData: {
    userInfo: null
  }
})

小程序的第42行代码无法执行,也就是无法打印请求成功
数据库使用的是mongodb。

分享到:
2条评论
Ctrl+Enter
作者

凉皮

凉皮

APP:0 帖子:2 回复:1 积分:70

已加入社区[2846]天

好吧来学技术的

作者详情》
Top