小程序前端开发Express+mongodb实现登录

小程序开发 前端 框架|小程序开发 前端框架|小程序视觉前端开发是什么意思

  1. 使用命令构建项目工程

express 你的项目路径

  1. 安装依赖的模块

cnpm install –save mongoose request moment

mongoose,用于连接mongoose数据库,对数据库进行增删改查
request,用于处理get和post请求
moment,对事件和日期进行格式化

  1. 连接 mongodb 数据库
    连接mongodb数据库
//app.js
var mongoose = require(“mongoose”);
mongoose.connect(
    “mongodb://127.0.0.1:27018/wechat_login”,
    function(err) {
        if (err) {
            console.info(“数据库连接失败”);
        } else {
            console.info(“数据库连接成功”);
        }
    },
);
  1. 具体逻辑部分实现
    (1)定义配置文件,即AppID和AppSecret
    小程序配置文件
var config = {
    AppID: “123215451541”,
    AppSecret: “hfjhdweoiufhiuoehf54546548”,
};

(2)自定义一个token生成函数(暂时使用此方法,真实项目中可以对openID进行MD5加密作为token)
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;
}

(3)如何从微信服务器获得openID
获取openid

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) {
            console.info(data.openid); //可以打印出openid;
        }
    },
);

(4)操作mongodb数据库
[1].schemas目录下新建users.js
定义users表的数据结构

//schemas->users.js
var mongoose = require(“mongoose”);
module.exports = new mongoose.Schema({
    openid: String,
    nickName: String,
    avatarUrl: String,
    creatAt: Date,
    token: String,
});

[2].models目录下新建User.js
javascript 代码

//models->User.js
var mongoose = require(“mongoose”);
var usersSchema = require(“../schemas/users”);
module.exports = mongoose.model(“User”, usersSchema);

[3].通过openid判断用户是否已经登陆过,如果,登陆过,则将用户信息返回给小程序端,如果没有登陆过,则保存用户信息,并把用户信息返回给小程序端
查询和保存用户数据

var User = require(“../models/User”);
User.findOne(
    {
        openid: data.openid,
    },
    function(err, info) {
        if (info) {
            var token = info.token;
            console.info(“用户已经存在”);
            res.send({ info: info });
        } else {
            var token = createToken();
            new User({
                openid: data.openid,
                nickName: param.nickname,
                avatarUrl: param.head_img,
                creatAt: param.creatAt,
                token: token,
            }).save(function(err, info) {
                res.send({ info: info });
            });
        }
    },
);

完整代码实现如下

完整代码如下

//index.js
var express = require(“express”);
var router = express.Router();
var request = require(“request”);
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: “458454545548545fgdve”,
    AppSecret: “jiedfhiue448654”,
};
//生成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, response, data) {
            if (res.statusCode === 200) {
                User.findOne(
                    {
                        openid: data.openid,
                    },
                    function(err, info) {
                        if (info) {
                            var token = info.token;
                            console.info(“用户已经存在”);
                            res.send({ info: info });
                        } else {
                            var token = createToken();
                            new User({
                                openid: data.openid,
                                nickName: param.nickname,
                                avatarUrl: param.head_img,
                                creatAt: param.creatAt,
                                token: token,
                            }).save(function(err, info) {
                                res.send({ info: info });
                            });
                        }
                    },
                );
            } else {
                console.info(“[error]”, err);
                res.json(err);
            }
        },
    );
});
module.exports = router;

小程序的前端开发框架|开发小程序前端需要做什么|小程序前端开发用什么语言

» 本文来自:前端开发者 » 《小程序前端开发Express+mongodb实现登录》
» 本文链接地址:https://www.rokub.com/4909.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!