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

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

  • 一、搭建环境
  • 二、配置Nodejs
  • 三、与小程序交互
  • 四、跨域处理/报错处理
  • 五、nodejs连接mysql数据库
  • 六、微信小程序连接nodejs报错
  • 七、小程序成功与服务端相连,且能操作数据库

一、搭建环境

  • 新建空文件夹: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) {
   
    

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/4a3f313e1a.html