You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LoopBackJS应用扩展内置User模型实现新用户注册并存储至MySQL

Hey there, let's walk through exactly how to set up user registration in your LoopBack test app that saves data straight to MySQL—since the docs and GitHub examples you've seen don't cover this properly.

实现LoopBack用户注册并存储到MySQL

1. 先确认MySQL数据源配置正确

First things first: you need to make sure your LoopBack app is connected to MySQL properly. If you haven't done this yet:

  • Run lb4 datasource in your project root, follow the wizard to select MySQL, then fill in your database credentials (host, port, database name, username, password).
  • Double-check the generated datasource file (like src/datasources/mysql.datasource.ts) to ensure the connection params are correct. You can even add debug: true to the settings to see connection logs in the console for verification.

2. 关联User模型到MySQL(扩展或直接用内置模型)

The default LoopBack User model uses an in-memory datasource—we need to point it to MySQL. If you want custom properties, extend the model; if not, just update the existing config:

Option A: Extend the User model (for custom attributes)

Run lb4 model, choose Extend an existing model, pick the User model, then add your desired fields (like phone, address). Make sure to set the datasource in the model decorator:

@model({
  settings: {
    datasource: 'mysql', // Replace with your MySQL datasource name
    strict: false,
  },
})
export class CustomUser extends User {
  @property({
    type: 'string',
    required: true,
  })
  phone: string;

  constructor(data?: Partial<CustomUser>) {
    super(data);
  }
}

Option B: Use the built-in User model directly

Find the User model's configuration file, update its datasource setting to point to your MySQL datasource instead of the default memory one.

3. 写一个注册接口Controller

Now let's build a controller to handle registration requests and save data to the database:
Run lb4 controller to create a UserRegistrationController, then add this code:

import {repository} from '@loopback/repository';
import {post, requestBody, response} from '@loopback/rest';
import {CustomUser} from '../models'; // Or use User if you didn't extend
import {CustomUserRepository} from '../repositories'; // Match your repository

export class UserRegistrationController {
  constructor(
    @repository(CustomUserRepository)
    public userRepo: CustomUserRepository,
  ) {}

  @post('/register')
  @response(201, {
    description: 'User registered successfully',
    content: {'application/json': {schema: {'x-ts-type': CustomUser}}},
  })
  async register(
    @requestBody({
      content: {
        'application/json': {
          schema: {
            type: 'object',
            required: ['email', 'password', 'phone'], // Adjust required fields to your needs
            properties: {
              email: {type: 'string'},
              password: {type: 'string'},
              phone: {type: 'string'},
              // Add other custom fields here
            },
          },
        },
      },
    })
    userData: Partial<CustomUser>,
  ): Promise<CustomUser> {
    // LoopBack's built-in User model automatically hashes passwords when using create()
    return this.userRepo.create(userData);
  }
}

4. 前端调用注册接口

From your frontend, send a POST request to the /register endpoint with user data. Here's a quick vanilla JS example:

async function handleRegister() {
  const userFormData = {
    email: 'test-user@example.com',
    password: 'secure-password-123',
    phone: '123-456-7890',
  };

  try {
    const res = await fetch('/register', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify(userFormData),
    });
    const registeredUser = await res.json();
    console.log('Registration successful:', registeredUser);
  } catch (err) {
    console.error('Registration failed:', err);
  }
}

5. Verify data is saved to MySQL

After testing a registration, log into your MySQL database and query the user table (default is User, or CustomUser if you extended the model) to confirm the new user record exists.

Quick Troubleshooting Tips

  • If data isn't saving: Check your datasource connection logs (enable debug: true in the datasource config) to ensure the app is connecting to MySQL.
  • Double-check that your repository is linked to the MySQL datasource.
  • Make sure the fields you're sending from the frontend match the model's property names exactly.

内容的提问来源于stack exchange,提问作者Sashi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:15:01