> 技术文档 > 使用Node.js+Mysql鸿蒙实现个人信息持久化_鸿蒙开放连接nodejs数据库

使用Node.js+Mysql鸿蒙实现个人信息持久化_鸿蒙开放连接nodejs数据库

  1. 前端(鸿蒙应用):通过 HTTP 请求与后端交互。

  2. 后端(Node.js):提供 RESTful API,处理业务逻辑并与 MySQL 数据库交互。

  3. 数据库(MySQL):存储用户信息等数据。

  4. 目录

    1. 后端(Node.js + MySQL)

    1.1 环境准备

    1.2 创建 Node.js 项目

    2. 前端(鸿蒙应用)

    2.1 创建 HTTP 工具类

    2.2 调用后端 API

    3. 运行流程


    1. 后端(Node.js + MySQL)

    1.1 环境准备

  1. 安装 Node.js 和 MySQL。

  2. 创建 MySQL 数据库和表:

CREATE DATABASE user_db;USE user_db;CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL, age INT, email VARCHAR(100));

1.2 创建 Node.js 项目

       初始化项目:

mkdir my-backendcd my-backendnpm init -y

       安装依赖

npm install express mysql body-parser cors

       创建index.js文件

const express = require(\'express\');const mysql = require(\'mysql\');const bodyParser = require(\'body-parser\');const cors = require(\'cors\');const app = express();const port = 3000;// 使用中间件app.use(bodyParser.json());app.use(cors());// 创建 MySQL 连接const db = mysql.createConnection({ host: \'localhost\', user: \'root\', // 替换为你的 MySQL 用户名 password: \'password\', // 替换为你的 MySQL 密码 database: \'user_db\'});db.connect((err) => { if (err) throw err; console.log(\'MySQL connected...\');});// 获取所有用户app.get(\'/users\', (req, res) => { const sql = \'SELECT * FROM users\'; db.query(sql, (err, results) => { if (err) throw err; res.json(results); });});// 添加用户app.post(\'/users\', (req, res) => { const { username, age, email } = req.body; const sql = \'INSERT INTO users (username, age, email) VALUES (?, ?, ?)\'; db.query(sql, [username, age, email], (err, result) => { if (err) throw err; res.json({ id: result.insertId, username, age, email }); });});// 更新用户app.put(\'/users/:id\', (req, res) => { const { username, age, email } = req.body; const sql = \'UPDATE users SET username = ?, age = ?, email = ? WHERE id = ?\'; db.query(sql, [username, age, email, req.params.id], (err, result) => { if (err) throw err; res.json({ id: req.params.id, username, age, email }); });});// 删除用户app.delete(\'/users/:id\', (req, res) => { const sql = \'DELETE FROM users WHERE id = ?\'; db.query(sql, [req.params.id], (err, result) => { if (err) throw err; res.json({ message: \'User deleted\' }); });});// 启动服务app.listen(port, () => { console.log(`Server running on http://localhost:${port}`);});

       运行后端服务:

node index.js

2. 前端(鸿蒙应用)

2.1 创建 HTTP 工具类

在鸿蒙应用中,使用 ohos.net.http 模块发送 HTTP 请求。

  1. 在 entry/src/main/java/com/example/myapplication 下创建 HttpUtil.java

package com.example.myapplication;import ohos.net.http.HttpRequest;import ohos.net.http.HttpResponse;import ohos.net.http.HttpClient;import ohos.hiviewdfx.HiLog;import ohos.hiviewdfx.HiLogLabel;import java.io.IOException;public class HttpUtil { private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0, \"HttpUtil\"); public static void sendRequest(String url, String method, String requestBody, HttpCallback callback) { new Thread(() -> { try { HttpClient httpClient = new HttpClient(); HttpRequest request = new HttpRequest(url); request.setMethod(method); if (requestBody != null) {  request.setHeader(\"Content-Type\", \"application/json\");  request.setBody(requestBody); } HttpResponse response = httpClient.execute(request); if (response.getResponseCode() == 200) {  String responseBody = response.getResult();  callback.onSuccess(responseBody); } else {  callback.onError(\"HTTP error: \" + response.getResponseCode()); } } catch (IOException e) { HiLog.error(LABEL, \"HTTP request failed: \" + e.getMessage()); callback.onError(e.getMessage()); } }).start(); } public interface HttpCallback { void onSuccess(String response); void onError(String error); }}

2.2 调用后端 API

在鸿蒙应用中调用后端的 RESTful API。

  1. 获取用户列表:

    String url = \"http://localhost:3000/users\";HttpUtil.sendRequest(url, \"GET\", null, new HttpUtil.HttpCallback() { @Override public void onSuccess(String response) { HiLog.info(LABEL, \"Users: \" + response); } @Override public void onError(String error) { HiLog.error(LABEL, \"Error: \" + error); }});
  2. 添加用户

    String url = \"http://localhost:3000/users\";String requestBody = \"{\\\"username\\\":\\\"John\\\",\\\"age\\\":25,\\\"email\\\":\\\"john@example.com\\\"}\";HttpUtil.sendRequest(url, \"POST\", requestBody, new HttpUtil.HttpCallback() { @Override public void onSuccess(String response) { HiLog.info(LABEL, \"User added: \" + response); } @Override public void onError(String error) { HiLog.error(LABEL, \"Error: \" + error); }});
  3. 删除用户

    String url = \"http://localhost:3000/users/1\"; // 替换为用户 IDString requestBody = \"{\\\"username\\\":\\\"JohnDoe\\\",\\\"age\\\":30,\\\"email\\\":\\\"johndoe@example.com\\\"}\";HttpUtil.sendRequest(url, \"PUT\", requestBody, new HttpUtil.HttpCallback() { @Override public void onSuccess(String response) { HiLog.info(LABEL, \"User updated: \" + response); } @Override public void onError(String error) { HiLog.error(LABEL, \"Error: \" + error); }});
  4. 修改用户

    String url = \"http://localhost:3000/users/1\"; // 替换为用户 IDString requestBody = \"{\\\"username\\\":\\\"JohnDoe\\\",\\\"age\\\":30,\\\"email\\\":\\\"johndoe@example.com\\\"}\";HttpUtil.sendRequest(url, \"PUT\", requestBody, new HttpUtil.HttpCallback() { @Override public void onSuccess(String response) { HiLog.info(LABEL, \"User updated: \" + response); } @Override public void onError(String error) { HiLog.error(LABEL, \"Error: \" + error); }});

3. 运行流程

  1. 启动 Node.js 后端服务。

  2. 在鸿蒙应用中调用 HTTP 工具类与后端交互。

  3. 后端服务处理请求并与 MySQL 数据库交互。


通过以上步骤,你可以在鸿蒙应用中实现个人信息持久化,并使用 MySQL 和 Node.js 作为后端支持。

 

IMTI在线培训