后端:获取小程序的用户openid

后端nodejs

// 路径:pro/router/wx.js
let express = require('express')
let router = express.Router()
let request  = require('request')

let config = {
  // 重要信息用X替代了
  appid:'wxa447XXXXXXXXXXXXXX',
  secret:'c1d99f1b05edb61XXXXXXXXXXXXXXX'
}

router.get('/getopenid',(req,res)=>{
        if(req.query.code){
          request({
                url:'https://api.weixin.qq.com/sns/jscode2session',
                qs: {
                  appid: config.appid,
                  secret: config.secret,
                  js_code: req.query.code,
                  grant_type: 'authorization_code'
                }
          },
          (err,response,body)=>{
                  if(err){
                    return res.json(err)
                  }
                  res.json(JSON.parse(body))
          })
        }
})

module.exports = router
// 路径: pro/serve.js
app.use(bodyParser.urlencoded({extended:false}))
// 创建静态资源目录
app.use(express.static(__dirname+'/public'))

app.all("*", function (req, res, next) {
     //设置允许跨域的域名,*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin", "*");
    //允许的header类型
    res.header("Access-Control-Allow-Headers", "content-type");
    //跨域允许的请求方式 
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options')
        res.send(200);
    else
        next();
})

app.get('/',(req,res)=>{
  res.send('hello World')
})

let router_user = require('./router/user.js')
app.use('/user',router_user)

let router_wx = require('./router/wx.js')
app.use('/wx',router_wx)

let router_sms = require('./router/sendSMS.js')
app.use('/getSMS',router_sms)

app.listen(8888,()=>{
  console.log('程序已启动')
})

前端:

    wx.login({
      success(res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: 'http://45.11.79.86:8888/wx/getopenid',
            data: {
              code: res.code
            },
            success(res) {
              console.log(res)
            },
            fail(err) {
              console.log(err)
            }
          })
        } else {
          console.log('登录失败!' + res.errMsg)
        }
      }
    })

结果:(openid不需要传给前端,后台将openid和手机号发短信绑定并存在数据库中)后端:获取小程序的用户openid_第1张图片

你可能感兴趣的:(后端)