这次主要是学习前后端交互等功能,对前端界面要求不多,仅一个按钮。
按钮绑定的事件名称为login
,下面看一下js代码:
// index.js
Page({
data: {
UserInfo: {}
},
login() {
console.log("点击登录");
wx.getUserProfile({
desc: 'desc',
lang: "zh_CN",
success: (result) => {
console.log(result.userInfo);
this.setData({
UserInfo: result.userInfo
})
wx.login({
success: (result) => {
wx.request({
url: 'http://127.0.0.1:3000/login',
method: "GET",
data: {
code: result.code
},
success: (result) => {
console.log(result)
wx.request({
url: 'http://127.0.0.1:3000/login/postUserInfo',
data: this.data.UserInfo,
method: 'POST',
success: (result) => {
console.log("上传成功");
}
})
}
})
}
})
}
})
}
})
代码还是很容易理解的,可以直接看微信官方文档相关内容,这里不在赘述。
{
"name": "tougao",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"devstart": "nodemon ./bin/www"
},
"dependencies": {
"body-parser": "^1.20.0",
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"jade": "~1.11.0",
"morgan": "~1.9.1",
"mysql": "^2.18.1",
"request": "^2.88.2"
},
"devDependencies": {
"nodemon": "^2.0.16"
}
}
先看一下依赖文件:
nodemon
:服务器自动刷新功能body-parse
:处理POST请求request
:像其他服务器发送请求express
:WEB框架mysql
:数据库再看脚本文件:
值得注意的就一个devstart
,主要是用来进行nodemon
自动刷新的
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var loginRouter = require('./routes/login')
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/login',loginRouter)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
其中自己添加的代码如下:
var bodyParser = require('body-parser')
var loginRouter = require('./routes/login')
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use('/login',loginRouter)
作用也很明显,分别为导入插件、导入路由、使用插件和路由。
其中就一个login路由。
var express = require('express');
var bodyParser = require('body-parser')
var request = require('request');
var router = express.Router();
var user_data_control=require('../db_control/user_data_control')
var app_id = "你的id"
var app_secret = "你的secret"
var base_url = 'https://api.weixin.qq.com/sns/jscode2session'
var userid;
/* GET users listing. */
router.get('/', function(req, res, next) {
var code = req.query.code
var url = base_url + '?appid=' + app_id + '&secret=' + app_secret + '&js_code=' + code +"&grant_type=authorization_code"
request(url, (error, response, body) => {
console.log('statusCode:', response && response.statusCode)
var thebody=JSON.parse(body)
console.log(thebody);
userid=thebody.openid
res.end(body)
})
});
router.post('/postUserInfo', function(req, res, next){
var userdata={
UnionId:userid,
name:req.body.nickName,
avatar:req.body.avatarUrl
}
console.log(userdata);
user_data_control.add_data(userdata);
})
module.exports = router;
代码主要分为四个部分:
代码也简介明了。
const mysql = require('mysql')
//创建连接
const conn = mysql.createConnection({
host: 'localhost',
port: 3306,
user: 'root',
password: '你的密码',
database: '你的数据库'
})
//连接mysql
conn.connect((err) => {
if (err) {
console.log(err)
return;
}
console.log('数据库链接成功!')
})
function add_data(userData){
var addSql = 'INSERT INTO userInfo(UnionId,name,avatar) VALUES(?,?,?)';
var addSqlParams = [userData.UnionId,userData.name,userData.avatar];
console.log(addSqlParams);
conn.query(addSql,addSqlParams,(err,res)=>{
if(err){
console.log(err.message);
return;
}
console.log('INSERT OK!'+res);
})
conn.end();
}
module.exports={
add_data
}
这是自己新学习到的,分别是数据库的连接、通过语句进行操作。
微信小程序向后端发送请求后,后端直接处理请求即可。# Express前后端开发