WeChat applet development tutorial: Using nodejs to implement the image path array acquisition function

Today's tutorial is the second part of the previous tutorial on obtaining group data. It mainly talks about the image path array allImagePaths that I created before. The way the code below obtains images is based on my uploading method of multiple images, and the way they are maintained in my database is as follows:

In the picture above, I uploaded two pictures on the front end of the WeChat applet, and they are both stored in the img column of the table in the mysql database. What we have to do next is to traverse the picture links named path in the img column. .

So now, I will officially teach you how to use WXML, WXSS, JavaScript (TypeScript) in the WeChat applet and the back-end Node.js code to achieve routing viagetdt The interface obtains the image path from the server and displays these images in the applet.

Preparation

  1. Make sure you already have a WeChat Mini Program project, if not, please create one first.
  2. Install and configure the Node.js environment and Express framework.
  3. Creategetdt.js the backend routing file and ensure it can correctly connect to the database and return data.

Step 1: Backend Node.js code

First, we need to ensure that the routing interface ingetdt.js can query data from the database and return an array of image paths.

// getdt.js
const express = require("express");
const router = express.Router();
const db = require("../sql");

router.get("/getdt", (req, res) => {
    const sql = "SELECT * FROM wxinfopen INNER JOIN wxusers ON wxinfopen.openid = wxusers.openid ORDER BY wxinfopen.iddt DESC";
    db.query(sql, (err, result) => {
        if (err) {
            console.log(err);
            res.status(500).json({ message: "获取数据失败" });
        } else {
            const allImagePaths = result.map((row) => {
                const imgArr = JSON.parse(row.img || "[]");
                return imgArr.map((imgObj) => "http://localhost:3000/" + imgObj.path.path);
            });
            res.status(200).json({ result, allImagePaths });
        }
    });
});

module.exports = router;

In the above code, const sql = "SELECT * FROM wxinfopen INNER JOIN wxusers ON wxinfopen.openid = wxusers.openid ORDER BY wxinfopen.iddt DESC"; you can directly simplify it to const sql = "SELECT * FROM wxinfopen";.

Here we pay attention to the code:

return imgArr.map((imgObj) => "http://localhost:3000/" + imgObj.path.path);

I mentioned my image upload method above. You may still remember that hereimgObj.path.path is an object attribute path parsed from the database query results. This path refers to the nested path attribute in each image object, which itself contains a path attribute. This inner pathThe attribute stores the actual file path of the image.

imgObj is an object that represents a record in the database and contains image information. In this object, the path attribute is an object containing multiple key-value pairs, and one of the keys is path, and its corresponding value is what we need The path to the image file.

Step 2: Mini program TS code

In the TypeScript file of the applet, we need to write a function to call the backend interface and process the returned data.

// 小程序TS文件
Page({
  data: {
    isShowForm: true,
    wxinfopenList: [], // 存储从后台获取的数据
    imgPaths: [], // 存储图片路径
    // 其他数据...
  },
  onLoad() {
    this.showForm();
  },
  showForm() {
    // 切换显示状态
    this.setData({
      isShowForm: !this.data.isShowForm
    });
    // 请求后端接口获取数据
    wx.request({
      url: '您的服务器地址/api/getdt',
      success: (res) => {
        const { result, allImagePaths } = res.data;
        this.setData({
          wxinfopenList: result,
          imgPaths: allImagePaths,
        });
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    });
  },
  // 其他方法...
});

Step 3: WXML code

In the WXML file, we need to write code to traverse the image path array returned by the backend and display the image.

<!-- WXML文件 -->
<view class="imgbox">
  <block wx:for="{
   
   {imgPaths[index]}}" wx:key="{
   
   {item}}" wx:for-index="itemIndex">
    <image class="img" src="{
   
   {item}}" bindtap="previewImage" data-index="{
   
   {index}}" data-item-index="{
   
   {itemIndex}}"></image>
  </block>
</view>

Here, we use the wx:for instruction to traverse the imgPaths[index] array, index is the current wxinfopenListThe index of the array item. wx:key is used to improve the performance of list rendering, itemIndex is the index of the image array.

When the code within <block> is executed, it will traverse the imgPaths[index] array, and each element will be assigned to a variableitem. Then, the attribute of the <image> tag will be set to the value of , which is the URL path of the current image. In this way, each will display the corresponding picture according to the value of . srcitem<image>item

Specifically, in this code:

  • <block wx:for="{ {imgPaths[index]}}">: This is a block-level element used to traverse the imgPaths[index] array. imgPaths is a two-dimensional array, where each element is also an array, containing all image paths corresponding to wxinfopenList entries. index is the current index of the outer wxinfopenList array.
  • wx:key="{ {item}}": This is an instruction that tells the applet how to update the list efficiently. { {item}} is used here as a unique identifier for each image element.
  • wx:for-index="itemIndex": This is the attribute that sets the inner loop index. itemIndex is the index in the currently traversed imgPaths[index] array.

Explain these too:

  • bindtap="previewImage": This is an event binding. When the user clicks on the picture, the function named previewImage will be triggered.
  • data-index="{ {index}}" and data-item-index="{ {itemIndex}}": These are custom data attributes that pass the outer array index and inner array index of the current image to the event handler function, so that the user can be known in the handler function Which picture was clicked.

The function here is to help me determine which picture the user clicked, and then open the corresponding picture preview. However, we will discuss the implementation of this function in the next article.

Step 4: WXSS code

We'll definitely need to add some styling to the images in the end to make sure they display correctly on the page. You can use the CSS style for your own reference:

/* WXSS文件 */
.imgbox {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}

.img {
  width: 100px;
  height: 100px;
  margin: 5px;
}

Step 5: Test the functionality

  1. Run your Node.js server.
  2. Run the mini program in WeChat developer tools.
  3. Call a showForm function (perhaps by clicking a button or loading a page).
  4. Check whether the image path can be obtained from the backend and display the image in the applet.

Through the above steps, we can achieve the function of obtaining image data from the server and displaying these images in the mini program. If you encounter problems, you check whether the server address is correct, whether the backend interface can work normally, and whether the mini program's request is sent and processed correctly.

Guess you like

Origin blog.csdn.net/qq_25501981/article/details/134748440