微信小程序开发教程:利用nodejs从mysql数据库获取一个数据,并显示到微信小程序

这是一个很基础的教程,将帮助你利用noidejs,从mysql数据库中获取想要的数据,并显示到微信小程序中。

而要实现微信小程序正确获取数据并显示到界面上,你还需要做以下修改:

  1. 确保你的微信小程序的 wx.request 方法是使用正确的 HTTP 方法(GET 或 POST)来请求数据。

  2. 更新 wx.request 中的 success 回调函数,以便使用返回的数据设置小程序页面的数据。

  3. 确保你的数据绑定在 WXML 中是正确的,以便能够显示从后端获取的数据。

微信小程序 TS 代码:

wx.request({
  url: config.apiUrl + '/api/pop',
  method: 'POST', // 指定请求方法为 POST
  success: (res) => {
    console.log(res.data);
    if (res.data && res.data.length > 0) {
      // 假设我们只显示第一条数据
      const adData = res.data[0];
      this.setData({
        item: adData, // 设置数据
        showAdPopup: true // 显示弹窗
      });
    }
  }
});

Node.js 的 pop 路由接口代码:

var express = require('express');
var router = express.Router();
var db = require('../sql.js');
router.post('/pop', function(req, res, next) {
    const sql = 'SELECT * FROM pop';
    db.query(sql, (error, results, fields) => {
        if (error) {
            throw error;
        }
        if (results.length > 0) {
            res.json(results);
        } else {
            res.status(404).json({ message: 'No data found' });
        }
    });
});
module.exports = router;

微信小程序的WXML代码,用于显示获取到的数据:

<view wx:if="{
   
   {showAdPopup && item}}" class="ad-popup">
  <view class="ad-popup-content">
    <text class="ad-popup-title">{
   
   {item.text}}</text>
    <image class="ad-popup-image" src="{
   
   {ImgUrl}}{
   
   {item.img}}" mode="aspectFit"></image>
    <view class="ad-popup-buttons">
      <button class="cancel-button" bindtap="closeAdPopup">关闭</button>
      <view class="spacer"></view>
      <button class="contact-button" bindtap="openCustomerServiceChat">咨询客服</button>
    </view>
  </view>
</view>

上面的代码中,{ {ImgUrl}}参数是构建的一个url路径字段,你可以在我之前发布的文章中,找到它的使用方法。点击这里可以去阅读:微信小程序开发教程:提高代码的可维护性和灵活性icon-default.png?t=N7T8https://mp.csdn.net/mp_blog/creation/editor/134728790

注意:{ {item.text}}中的text,对应mysql数据库pop表中的text字段,{ {item.img}}同理。

最后,确保你的微信小程序的服务器域名已经添加到微信公众平台的服务器域名白名单中,否则请求会因为域名不在白名单中而失败。

完成上述修改后,你的小程序应该能够正确地从 Node.js 服务器获取数据并在界面上显示出来。

猜你喜欢

转载自blog.csdn.net/qq_25501981/article/details/134728961