Angular项目后端用sqlite3遇模块解析错误的解决问询
前置说明
- 在常规Node应用中,sqlite3模块可正常工作。
- 不想在浏览器中访问数据库,数据库将部署在后端。
- 本人是Node和Angular新手。
遇到的错误
尝试在Angular项目中使用node-sqlite3时,出现大量类似如下的编译错误:
node_modules/tar/lib/pack.js:54:13-28 - Error: Module not found: Error: Can't resolve 'path' in '[...]\node_modules\tar\lib' BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it. If you want to include a polyfill, you need to: - add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }' - install 'path-browserify' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "path": false } ./node_modules/tar/lib/parse.js:32:4-22 - Error: Module not found: Error: Can't resolve 'process' in '[...]\node_modules\tar\lib' BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it. If you want to include a polyfill, you need to: - add a fallback 'resolve.fallback: { "process": require.resolve("process/browser") }' - install 'process' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "process": false }
此类错误数量众多。
版本信息
>ng version _ _ ____ _ ___ / \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _| / △ \ | '_ \ / _` | | | | |/ _` | '__| | | | | | | / ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | | /_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___| |___/ Angular CLI: 16.2.5 Node: 20.6.1 (Unsupported) Package Manager: npm 9.8.1 OS: win32 x64 Angular: 16.2.8 ... animations, common, compiler, compiler-cli, core, forms ... platform-browser, platform-browser-dynamic, router Package Version --------------------------------------------------------- @angular-devkit/architect 0.1602.5 @angular-devkit/build-angular 16.2.5 @angular-devkit/core 16.2.5 @angular-devkit/schematics 16.2.5 @angular/cli 16.2.5 @schematics/angular 16.2.5 rxjs 7.8.1 typescript 5.1.6 zone.js 0.13.3
问题复现步骤
- 按照Angular官方指南创建新项目(接受默认配置):
ng new my-app cd my-app ng serve --open
项目可正常运行。
2. 执行npm install sqlite3安装node-sqlite3。
3. 创建src/db.ts文件,内容如下:
import * as sqlite3 from 'sqlite3'; const db = new sqlite3.Database('file.db'); export function test(): void { db.run(`CREATE TABLE IF NOT EXISTS Test ( id INTEGER PRIMARY KEY, text TEXT UNIQUE NOT NULL ) STRICT;` ); db.run('INSERT INTO Test VALUES (NULL, ?)', 'Hello, world'); db.each('SELECT * FROM Test', (err, row) => { console.log('Test data', row); }); }
- 在
app.component.ts中调用该函数(例如在构造函数中):
import { test } from 'src/db'; //... constructor() { test(); }
- 再次执行
ng serve --open,控制台出现大量错误信息。
尝试过自定义构建器但仅获得部分成功且引入其他问题;将数据访问代码放入Angular服务中,问题依旧。
核心疑问
如何在使用Angular作为前端的同时,在后端使用SQLite?不想引入其他库,该如何配置sqlite3或Angular来实现这一需求?
你现在的核心问题是把后端的SQLite代码写到了Angular前端项目里,Angular是前端框架,构建时会把代码打包成浏览器能运行的文件,但sqlite3是Node.js后端模块,依赖Node核心API(比如path、process),这些API在浏览器环境不存在,所以才会报缺失模块的错误。
要解决这个问题,你需要把SQLite的操作和Angular前端彻底分开,步骤如下:
1. 单独搭建Node后端服务
在你的Angular项目外,或者项目内创建一个独立的后端文件夹(比如backend),初始化Node项目:
mkdir backend cd backend npm init -y npm install sqlite3 express cors
2. 编写后端API接口
在backend文件夹下创建server.js,实现SQLite操作和API接口:
const express = require('express'); const cors = require('cors'); const sqlite3 = require('sqlite3').verbose(); const app = express(); app.use(cors()); app.use(express.json()); // 连接SQLite数据库 const db = new sqlite3.Database('./file.db', (err) => { if (err) console.error(err.message); console.log('Connected to the SQLite database.'); // 初始化表 db.run(`CREATE TABLE IF NOT EXISTS Test ( id INTEGER PRIMARY KEY, text TEXT UNIQUE NOT NULL ) STRICT;`); }); // 新增数据接口 app.post('/api/test', (req, res) => { const { text } = req.body; db.run('INSERT INTO Test VALUES (NULL, ?)', [text], function(err) { if (err) return res.status(500).json({ error: err.message }); res.json({ id: this.lastID, success: true }); }); }); // 查询数据接口 app.get('/api/test', (req, res) => { db.all('SELECT * FROM Test', [], (err, rows) => { if (err) return res.status(500).json({ error: err.message }); res.json(rows); }); }); const PORT = 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
3. 启动后端服务
在backend文件夹下执行:
node server.js
4. Angular前端调用后端API
修改Angular的代码,去掉直接引入sqlite3的部分,改用HttpClient调用后端接口:
首先在Angular项目中导入HttpClientModule:
在app.module.ts中添加:
import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ // ...其他导入 HttpClientModule ], // ... }) export class AppModule { }
然后创建一个Angular服务(比如data.service.ts):
ng generate service data
修改data.service.ts内容:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class DataService { private baseUrl = 'http://localhost:3000/api'; constructor(private http: HttpClient) { } addTestData(text: string): Observable<any> { return this.http.post(`${this.baseUrl}/test`, { text }); } getTestData(): Observable<any[]> { return this.http.get<any[]>(`${this.baseUrl}/test`); } }
最后在app.component.ts中调用服务:
import { Component } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(private dataService: DataService) { // 新增数据 this.dataService.addTestData('Hello, world').subscribe(res => { console.log('新增成功', res); // 查询数据 this.dataService.getTestData().subscribe(data => { console.log('Test数据', data); }); }); } }
5. 启动Angular项目
回到Angular项目根目录,执行:
ng serve --open
这样就能实现Angular前端通过API调用后端的SQLite数据库,完全符合你的需求——数据库部署在后端,不需要额外引入其他不必要的库。
内容的提问来源于stack exchange,提问作者S4NR-3000

