My WeChat Mini Program Journey – Part 2: Setting Up the Back-End

As part of my ongoing project to develop a WeChat mini program (Project: StudHubPro) for managing student attendance at a study hub, I recently completed the setup of the back-end system. This blog post documents the key steps I took to configure the server, create the database, and debug some tricky proxy issues with Apache. Hopefully, this can serve as a guide for others venturing into similar projects.

1. Setting Up the Environment

Server Setup

For this project, I had already set up an Ubuntu server with Apache, using an SSL certificate via Certbot for HTTPS support. The server was prepared to handle secure connections, and I planned to use Flask for my back-end, with MySQL to store user data.

MySQL Database

The first step in the back-end setup was to create the necessary database and table structures. Here’s a quick summary of the process:

  1. Create Database:
   CREATE DATABASE studhubpro;
   USE studhubpro;
  1. Create Table students:
   CREATE TABLE students (
       student_id VARCHAR(255) PRIMARY KEY,
       name VARCHAR(100),
       phone_number VARCHAR(50),
       signup_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
   );

After successfully setting up MySQL and creating the table, I moved on to develop the API that would allow the WeChat mini program to register users and log them into the system.

2. Developing the Flask API

I created a simple Flask API to handle the user registration logic. The API receives user data from the front end, stores it in the students table, and returns a success message.

Here’s the core part of the app.py file that defines the register route:

from flask import Flask, request, jsonify
import pymysql

app = Flask(__name__)

# User registration API
@app.route('/wxmini/studhubpro-api/register', methods=['POST'])
def register():
    data = request.json
    user_info = data['userInfo']
    code = data['code']

    # Connect to MySQL
    connection = pymysql.connect(
        host='localhost',
        user='root',
        password='yourpassword',
        db='studhubpro'
    )
    with connection.cursor() as cursor:
        sql = "INSERT INTO students (student_id, name, phone_number, signup_date) VALUES (UUID(), %s, %s, NOW())"
        cursor.execute(sql, (user_info['nickName'], ''))
        connection.commit()

    return jsonify({'message': 'Registration successful'})

I made sure to configure the MySQL credentials through a config.json file for flexibility and security. Flask was up and running smoothly, and I could test everything locally via curl or Postman.

3. Proxy Issue: Encountering the Apache 404

After getting everything set up locally, I faced a frustrating issue when trying to access my API over the web. My API endpoint kept returning 404 Not Found errors when accessed via the domain https://www.ruianding.com/wxmini/studhubpro-api/register.

The Problem

  • Locally, I was able to call curl http://127.0.0.1:8000/wxmini/studhubpro-api/register without any issues. This indicated that the Flask app and MySQL connection were functioning perfectly.
  • However, when I tried to access the same route through Apache using HTTPS, I was getting 404 errors.

The Solution: Fixing Apache’s ProxyPass

After carefully reviewing the Apache configuration and examining the error logs, I realized the problem stemmed from how the proxy was handling the path. Here’s what I originally had in my Apache configuration:

ProxyPass "/wxmini/studhubpro-api" "http://127.0.0.1:8000"
ProxyPassReverse "/wxmini/studhubpro-api" "http://127.0.0.1:8000"

This setup works fine for simple, static paths, but for paths like /wxmini/studhubpro-api/test or dynamic segments, it can cause issues.

Switching to ProxyPassMatch

The solution was to use ProxyPassMatch, which allows you to handle dynamic or complex paths by using regular expressions. Here’s the updated configuration that finally solved the problem:

ProxyPassMatch "^/wxmini/studhubpro-api/(.*)$" "http://127.0.0.1:8000/wxmini/studhubpro-api/$1"

This configuration ensured that any request to /wxmini/studhubpro-api/* would be properly forwarded to the Flask application running on port 8000.

Debugging with Logs

To further debug the issue, I enabled detailed logging in Apache using:

LogLevel proxy:debug

By inspecting the logs, I could confirm that the requests were now being properly proxied to Flask, and the 404 errors were gone.

4. Testing the GET API

To verify the success of the fix, I set up a simple GET API in Flask:

@app.route('/wxmini/studhubpro-api/test', methods=['GET'])
def test_route():
    return jsonify({'message': 'xiaowu'})

After reloading the server, I successfully tested the endpoint using:

curl -X GET https://www.ruianding.com/wxmini/studhubpro-api/test

This returned:

{
    "message": "xiaowu"
}

Everything worked perfectly!

5. Conclusion and Lessons Learned

This part of the project taught me some valuable lessons about configuring web servers, proxying requests with Apache, and debugging issues effectively. The key takeaway here was understanding how Apache’s ProxyPass and ProxyPassMatch work and when to use each.

By using ProxyPassMatch, I was able to route all requests correctly to my Flask API and finally connect my WeChat mini program with the back-end database.

Next Steps

Now that the API and database are up and running, the next phase of this project will involve expanding the functionality to handle student attendance logging and data analysis. I’ll also implement a secure login system, and possibly add session management or token-based authentication for security.

Stay tuned for the next update in my WeChat mini program development journey!