zoukankan      html  css  js  c++  java
  • 微信小程序+express获取token值

    安装 request,express,body-parser

    cnpm install express request body-parser  --save

    引入及使用

    app.js文件中

    const express =require("express");
    const request=require("request");
    
    const app=express();
    const bodyParser=require("body-parser");
    app.use(bodyParser.urlencoded({extended:false}));
    app.use(bodyParser.json());
    
    //定义appid  和appSecret;
    const appid="wx*******";
    const appSecret="f8****************";
    
    app.get("/api/login",(req,res,next)=>{
    const code=req.query.code;
    const url=`https;//api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`;
    request(url,(err,wxresult,body)=>{
        res.send({
            code:1,
            msg:'请求数据成功",
            data:body
        })
        })
    })

    //发送token值
    app.get("/api/userToken",(req,res,next)=>{
    const tokenUrl=`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appSecret}`;
    request(tokenUrl,(err,wxres,body)=>{
    res.send({
    code:1,
    msg:'操作成功',
    data:body
    })
    })
    })

    
    
    app.listen(3001,()=>{
        console.log('app is start");
    })

    me.js文件

    // pages/me/me.js
    Page({
    
      /**
       * 页面的初始数据
       */
      data: {
        baseUrl: getApp().globalData.baseUrl,
        isShow: false,
        userName: "游客",
        userInfo: {},
      },
    
      // 获取用户信息
      handlerGetUserInfo(e) {
        var that = this
        console.log(e)
    
        if (e.detail.errMsg == "getUserInfo:ok") {
          var newData = { userName: e.detail.userInfo.nickName, avatar: e.detail.userInfo.avatarUrl }
    
          // 收取获取用户信息
          wx.login({
            success: res => {
              console.log(res)
              const code = res.code
              // console.log(that.data.baseUrl + "api/login?code=" + code + "&userName=" + newData.userName + "&avatar=" + newData.avatar)
              wx.request({
                url: that.data.baseUrl + "api/login?code=" + code,
                success: res => {
                  console.log(res)
                  const openid = JSON.parse(res.data.data).openid
                  const session_key = JSON.parse(res.data.data).session_key
                  wx.setStorageSync("openid", openid)
                  wx.setStorageSync("session_key", session_key)
                  that.setData({
                    isShow: true,
                    userInfo: newData
                  })
              
            // 获取token值
                  wx.request({
                    url: that.data.baseUrl+"api/userToken",
                    method:'GET',
                    success:res=>{
                      console.log(res)
                      // 保存token值
                      wx.setStorageSync('token', JSON.parse(res.data.data).access_token)
                    }
                  })
    // 保存用户信息
                  wx.request({
                    url: that.data.baseUrl + "api/saveInfo",
                    method: "POST",
                    data: newData,
                    success: saveRes => {
                      console.log(saveRes)
                      wx.setStorageSync('userInfo', saveRes.data.list[0])
                    }
                  })
                }
              })
            }
          })
        } else {
    
        }
      },
    
      /**
       * 生命周期函数--监听页面加载
       */
      onLoad: function (options) {
    
      },
    
      /**
       * 生命周期函数--监听页面初次渲染完成
       */
      onReady: function () {
    
      },
    
      /**
       * 生命周期函数--监听页面显示
       */
      onShow: function () {
        // 判断用户是否登录
        var userInfo = wx.getStorageSync('userInfo')
        if (!userInfo) {
    
        } else {
          this.setData({
            isShow: true,
            userInfo: userInfo
          })
        }
      },
    
      /**
       * 生命周期函数--监听页面隐藏
       */
      onHide: function () {
    
      },
    
      /**
       * 生命周期函数--监听页面卸载
       */
      onUnload: function () {
    
      },
    
      /**
       * 页面相关事件处理函数--监听用户下拉动作
       */
      onPullDownRefresh: function () {
    
      },
    
      /**
       * 页面上拉触底事件的处理函数
       */
      onReachBottom: function () {
    
      },
    
      /**
       * 用户点击右上角分享
       */
      onShareAppMessage: function () {
    
      }
    })

    me.wxml

    <view class="header" wx:if="{{isShow}}">
          <image src="{{userInfo.avatar}}" class="user-img"></image>
          <view class="user-name">{{userInfo.userName}}</view>
     </view>
     <view class="header"wx:if="{{!isShow}}">
          <image src="" class="user-img"></image>
          <button class="like-btn-user-name" open-type="getUserInfo" bindgetuserinfo="handlerGetUserInfo">游客登录</button>
    </view>



  • 相关阅读:
    LeetCode 172. Factorial Trailing Zeroes
    C++primer 练习12.27
    C++primer 练习12.6
    C++primer 练习11.33:实现你自己版本的单词转换程序
    77. Combinations
    75. Sort Colors
    74. Search a 2D Matrix
    73. Set Matrix Zeroes
    71. Simplify Path
    64. Minimum Path Sum
  • 原文地址:https://www.cnblogs.com/shanchui/p/13697420.html
Copyright © 2011-2022 走看看