小程序使用Nodejs作为服务端,Nodejs与MYSQL数据库相连
一、搭建环境
- 新建空文件夹:Win + R进入cmd命令界面执行
npm install express body-parser request
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/fe79d3df15b8302ca72803358a17a77c.png)
二、配置Nodejs
const express = require('express')
const bodyParser = require('body-parser')
const request = require('request')
const app = express()
const PORT = 5008
app.use(bodyParser.json())
app.get('/',(req,res)=>{
res.send('Server is running!')
})
app.listen(PORT,()=>{
console.log(`Server is running on localhost:${
PORT}`);
})
- 启动Nodejs:在终端输入
node index.js
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7c52e8465ff29b79a22964316898a24f.png)
三、与小程序交互
const APP_ID = "wx4f9ef75353fd5bc3";
const APP_SECRET = "d9317db76db37df632d729ca0bdf1f2a";
app.get("access_token", (req, res) => {
const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${
APP_ID}&secret=${
APP_SECRET}`;
request.get(url, (error, response, body) => {
if (!error && response.statusCode === 200) {
const {
access_token } = JSON.parse(body);
res.js