制作ChatPDF之后端Node搭建(三)

后端Node搭建

接上篇:制作ChatPDF之前端Vue搭建(二)

项目结构

下面是项目的结构图,包括前端 (Vue.js) 和后端 (Node.js) 的项目结构。

pdf-query-app/
├── frontend/
│   ├── public/
│   │   ├── index.html
│   ├── src/
│   │   ├── assets/
│   │   ├── components/
│   │   │   └── PdfUploader.vue
│   │   ├── App.vue
│   │   ├── main.js
│   ├── package.json
│   ├── vue.config.js
├── backend/
│   ├── uploads/         // 存放上传的临时文件
│   ├── server.js        // 主服务器文件
│   ├── package.json     // Node.js 项目的依赖配置
├── elasticsearch/
│   └── docker-compose.yml  // Elasticsearch 配置(可选)

1. 初始化 Node.js 项目

首先,确保你已经安装了 Node.js 和 npm。如果没有,请从 Node.js 官方网站 下载并安装。

创建项目目录
mkdir pdf-query-backend
cd pdf-query-backend
初始化项目

使用 npm 初始化项目,这将创建一个 package.json 文件。

npm init -y

2. 安装依赖

安装 Express 框架、Multer 中间件、pdf-parse 库和 Elasticsearch 客户端库。

npm install express multer pdf-parse @elastic/elasticsearch

3. 创建项目目录结构

设置项目目录结构,确保目录结构清晰,易于维护。

pdf-query-backend/
├── uploads/               # 存放上传的临时文件
├── routes/
│   └── pdfRoutes.js       # 路由文件
├── server.js              # 主服务器文件
├── package.json           # 项目依赖配置
├── package-lock.json      # 锁定的依赖配置

4. 创建服务器文件

server.js

创建一个主服务器文件 server.js,用于启动 Express 服务器并处理文件上传和查询请求。

const express = require('express');
const multer = require('multer');
const pdfParse = require('pdf-parse');
const { Client } = require('@elastic/elasticsearch');
const fs = require('fs');
const path = require('path');
const pdfRoutes = require('./routes/pdfRoutes');

const app = express();
const upload = multer({ dest: 'uploads/' });
const client = new Client({ node: 'http://localhost:9200' });

// 使用路由
app.use('/pdf', pdfRoutes(client, upload));

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});
routes/pdfRoutes.js

创建一个新的路由文件 pdfRoutes.js,用于处理 PDF 文件上传和查询请求。

const express = require('express');
const fs = require('fs');
const pdfParse = require('pdf-parse');
const path = require('path');

module.exports = (client, upload) => {
  const router = express.Router();

  // 处理文件上传
  router.post('/upload', upload.single('file'), async (req, res) => {
    try {
      const fileBuffer = fs.readFileSync(req.file.path);
      const data = await pdfParse(fileBuffer);

      await client.index({
        index: 'pdfs',
        body: {
          content: data.text,
          filename: req.file.originalname,
          uploadDate: new Date()
        }
      });

      fs.unlinkSync(req.file.path); // 删除临时文件
      res.json({ message: 'File uploaded and indexed successfully.' });
    } catch (error) {
      res.status(500).json({ error: 'Error processing file.' });
    }
  });

  // 处理查询请求
  router.get('/search', async (req, res) => {
    const { q } = req.query;
    try {
      const { body } = await client.search({
        index: 'pdfs',
        body: {
          query: {
            match: { content: q }
          }
        }
      });
      res.json(body);
    } catch (error) {
      res.status(500).json({ error: 'Error searching for query.' });
    }
  });

  return router;
};

5. 运行项目

确保 Elasticsearch 正在运行,并启动你的 Node.js 服务器。

node server.js

你的服务器现在应该在 http://localhost:3000 上运行,你可以通过 POST 请求上传 PDF 文件,通过 GET 请求查询索引内容。

6. 测试 API

上传 PDF 文件

使用 Postman 或 cURL 测试文件上传 API:

curl -X POST http://localhost:3000/pdf/upload -F 'file=@/path/to/your/file.pdf'
查询 PDF 内容

使用浏览器或 Postman 测试查询 API:

http://localhost:3000/pdf/search?q=your-query

启动

报错如下cors error:

在这里插入图片描述

在你的 Node.js 服务器上启用 CORS。你可以使用 cors 中间件来实现这一点。

解决方法

1. 安装 cors 中间件

在你的 Node.js 项目中安装 cors 中间件:

sh
复制代码
npm install cors
2. 配置 cors 中间件

server.js 中配置 cors 中间件:

const cors = require('cors');
// 启用 CORS
app.use(cors());

测试

  1. 启动后端服务器

    node server.js
    
  2. 启动前端开发服务器

    npm run serve
    
  3. 访问前端应用

    打开浏览器,访问 http://localhost:8080,上传 PDF 文件并进行查询。

    在这里插入图片描述

    文件上传成功,解析内容成功。
    在这里插入图片描述

储存在elasticsearch里面以index:pdfskey

在这里插入图片描述

但是search返回对象为null

在这里插入图片描述

分析:

1. 插件原因

Elasticsearch 中索引和搜索 PDF 文件的内容,需要安装 ingest-attachment 插件。

  1. 停止 Elasticsearch 服务:在安装插件之前,首先停止 Elasticsearch 服务。

  2. 安装插件:在命令行中运行以下命令来安装 ingest-attachment 插件:

    bin/elasticsearch-plugin install ingest-attachment
    

    这将下载并安装 ingest-attachment 插件。

  3. 重新启动 Elasticsearch 服务:安装完成后,重新启动 Elasticsearch 服务以使插件生效。

    bin/elasticsearch
    

结果报错

-> Installing ingest-attachment
[ingest-attachment] is no longer a plugin but instead a module packaged with this distribution of Elasticsearch
-> Please restart Elasticsearch to activate any plugins installed

对于elasticsearch8.13.4里面,ingest-attachment插件已经被整合为 Elasticsearch 的一个模块,并随着 Elasticsearch 分发的一部分而不是作为一个单独的插件。因此,你不需要手动安装它。

  • 26
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值