小程序使用Nodejs作为服务端,Nodejs与与MYSQL数据库相连

一、搭建环境

  • 新建空文件夹:Win + R进入cmd命令界面执行npm install express body-parser request
    在这里插入图片描述

二、配置Nodejs

  • 目录下新建index.js文件,并配置如下代码:
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
    在这里插入图片描述

三、与小程序交互

  • 服务端代码实现:依旧在index.js文件中
// 小程序设置
const APP_ID = "wx4f9ef75353fd5bc3";
const APP_SECRET = "d9317db76db37df632d729ca0bdf1f2a";

// 获取access_token
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) {
   
    
    
    

猜你喜欢

转载自blog.csdn.net/m0_50298323/article/details/134581675