Express代理转发服务器实现

来自:网络
时间:2023-05-17
阅读:
目录

express的代理转发

其实我的内心关于这个Express,我的内心是拒绝的,不是说,我对这个框架有什么看法,而是因为这个大作业的问题。是的我还是一个大三老菜鸡,苦练 Java 全干开发,Python 人工智能 整整 一坤年。期间拿了几个奖,水了篇论文 而已。

那么这篇文章主要做的,其实很简单就是,做个代理转发。前端请求,先到express服务器,然后转发到flask服务器,为什么非要转发呢,原因很简单,web作业非要用node平台,没办法,但是我的服务已经用flask做好了,当然这个和我先前写的那个微信聊天的不一样哈,这个是另一个,是视觉识别算法,说到这个,我本人目前也在手写一个全新的目标检测算法,希望可以起到不错的效果,扯远了。所以没有办法,只能做一个express的代理转发。

但是呢,为了体现工作量,我在这个转发服务器里面加了点东西:

Express代理转发服务器实现

就是这个,加点curd,不然不好混。

项目结构

这个的话,更像是一个dome,所以的话,项目结构非常简单。

Express代理转发服务器实现

因为核心功能就一个,就是做转发,然后呢,加上一些配套的记录就好了。

然后就是我们的数据库还有页面之类的。当然整个项目还是使用这个生成工具先生成了一个模板工程的。

由于整个项目简单,骨架也是生成的,所以我这边就只说,它的一些核心实现了。

转发

那么首先就是我们的核心,代理转发:

const proxy = require("http-proxy-middleware").createProxyMiddleware;
app.use(
    "/",
    proxy(
        [`/api/**`], {
            target: `http://www.httpbin.org/anything/`,
            changeOrigin: true,
            onProxyReq: (proxyReq, req, res) => {
                // 在代理请求发送到目标服务器之前,对请求头进行修改
                const sourceUrl = req.originalUrl;
                const targetUrl = "your address";
                db.insertProxy(sourceUrl, targetUrl, (err, id) => {
                    if (err) {
                        console.error(err);
                    } else {
                        console.log(`New proxy request saved with ID ${id}.`);
                    }
                });
            },
            onProxyRes: (proxyRes, req, res) => {
                // 在代理服务器收到目标服务器的响应后,对响应头进行修改
                proxyRes.headers['x-custom-header'] = 'Huterox';
            }
        },
    ),
);

转发记录

然后其实就是我们的转发记录的了。这里的话我使用的是sqlite3。

这边把一些方法都封装到了db.js当中去了。

const sqlite3 = require('sqlite3').verbose();
// 创建数据库连接
const db = new sqlite3.Database('./db.sqlite', err => {
    if (err) {
        console.error(err.message);
    } else {
        console.log('Connected to the db.sqlite database.');
    }
});
// 创建表
const createTable = () => {
    db.run(
        `CREATE TABLE IF NOT EXISTS proxies (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      source_url TEXT NOT NULL,
      target_url TEXT NOT NULL,
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )`,
        err => {
            if (err) {
                console.error(err.message);
            } else {
                console.log('Table proxies created successfully.');
            }
        }
    );
};
//查找
const searchProxy = function(keyword, offset, limit, callback) {
    const pattern = `%${keyword}%`;
    const countSql = `SELECT COUNT(*) as count FROM proxies WHERE source_url LIKE ? OR target_url LIKE ?`;
    const sql = `SELECT * FROM proxies WHERE source_url LIKE ? OR target_url LIKE ? ORDER BY created_at DESC LIMIT ? OFFSET ?`;
    db.get(countSql, [pattern, pattern], (err, row) => {
        if (err) {
            callback(err, {});
            return;
        }
        const totalCount = row.count;
        db.all(sql, [pattern, pattern, limit, offset], (err, rows) => {
            if (err) {
                callback(err);
                return;
            }
            const proxies = rows.map(row => ({
                id: row.id,
                sourceUrl: row.source_url,
                targetUrl: row.target_url,
                createdAt: row.created_at,
            }));
            callback(null, { proxies, totalCount });
        });
    });
};
// 插入一条记录
const insertProxy = (sourceUrl, targetUrl, callback) => {
    db.run(`INSERT INTO proxies (source_url, target_url) VALUES (?, ?)`, [sourceUrl, targetUrl], err => {
        if (err) {
            console.error(err.message);
            callback(err.message, null);
        } else {
            console.log('New proxy added successfully.');
            db.get(`SELECT last_insert_rowid() as id`, (err, row) => {
                callback(null, row.id);
            });
        }
    });
};
// 根据 ID 查询代理转发记录
const getProxyById = (id, callback) => {
    db.get(`SELECT * FROM proxies WHERE id = ?`, [id], (err, row) => {
        if (err) {
            console.error(err.message);
            callback(err.message, null);
        } else {
            console.log(`Proxy with ID ${id} found.`);
            callback(null, row);
        }
    });
};
// 查询所有代理转发记录
const getAllProxies = callback => {
    db.all(`SELECT * FROM proxies ORDER BY id`, (err, rows) => {
        if (err) {
            console.error(err.message);
            callback(err.message, null);
        } else {
            console.log('All proxies fetched successfully.');
            callback(null, rows);
        }
    });
};
// 更新代理转发记录
const updateProxyById = (id, sourceUrl, targetUrl, callback) => {
    db.run(
        `UPDATE proxies SET source_url = ?, target_url = ? WHERE id = ?`, [sourceUrl, targetUrl, id],
        err => {
            if (err) {
                console.error(err.message);
                callback(err.message, null);
            } else {
                console.log(`Proxy with ID ${id} updated successfully.`);
                callback(null, true);
            }
        }
    );
};
// 根据 ID 删除代理转发记录
const deleteProxyById = (id, callback) => {
    db.run(`DELETE FROM proxies WHERE id = ?`, [id], err => {
        if (err) {
            console.error(err.message);
            callback(err.message, null);
        } else {
            console.log(`Proxy with ID ${id} deleted successfully.`);
            callback(null, true);
        }
    });
};
createTable();
module.exports = {
    insertProxy,
    getProxyById,
    getAllProxies,
    searchProxy,
    updateProxyById,
    deleteProxyById
};

当然只有这个还不够,我们还有对应的curd的接口才行。

所以在app.js里面去注册这些接口。

app.get('/logs/proxy', (req, res) => {
    const { keyword = '', offset = 0, limit = 10 } = req.query;
    db.searchProxy(keyword, Number(offset), Number(limit), (err, result) => {
        if (err) {
            console.error(err);
            res.status(500).send('Internal server error.');
        } else {
            res.json({
                rows: result.proxies,
                count: result.totalCount
            });
            console.log("当前记录条数:" + result.totalCount)
        }
    });
});
app.post('/logs/proxy', (req, res) => {
    const { sourceUrl, targetUrl } = req.body;
    db.insertProxy(sourceUrl, targetUrl, (err, row) => {
        if (err) {
            console.error(err);
            res.status(500).send('Internal server error.');
        } else {
            res.json(row);
        }
    });
});
app.delete('/logs/proxy/:id', (req, res) => {
    const id = req.params.id;
    db.deleteProxy(id, (err) => {
        if (err) {
            console.error(err);
            res.status(500).send('Internal server error.');
        } else {
            res.status(204).end();
        }
    });
});

前端页面

之后,就是我们的前端页面,这个页面的话,好办,我们就直接使用html来写了。 访问/logs 就可以访问页面:

app.get('/logs', (req, res) => {
    res.sendFile(__dirname + '/public/logs.html');
});

对应的html代码如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>代理日志查看</title>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css" rel="external nofollow" >
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>
<style>
    /* 设置全局字体和颜色 */
    #app {
        margin: 0 auto;
        width: 80%;
    }
</style>
<body>
    <div id="app">
        <h1>代理日志</h1>
        <el-form inline>
            <el-form-item label="关键字">
                <el-input v-model="keyword" placeholder="输入关键字进行搜索"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" v-on:click="search">搜索</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="records" stripe>
            <el-table-column prop="id" label="ID" width="100"></el-table-column>
            <el-table-column prop="sourceUrl" label="请求路径" width="300"></el-table-column>
            <el-table-column prop="targetUrl" label="目标地址" width="300"></el-table-column>
            <el-table-column prop="timestamp" label="时间" width="200">
                <template slot-scope="scope">{{ new Date(scope.row.createdAt).toLocaleString() }}</template>
            </el-table-column>
            <el-table-column label="操作" width="200">
                <template slot-scope="scope">
          <el-button type="danger" icon="el-icon-delete" v-on:click="removeRecord(scope.row.id)">删除</el-button>
        </template>
            </el-table-column>
        </el-table>
        <el-pagination layout="total, prev, pager, next" :total="total" v-on:current-change="changePage"></el-pagination>
    </div>
    <script>
        const app = new Vue({
            el: '#app',
            data: {
                records: [],
                keyword: '',
                current: 1,
                pageSize: 10,
                total: 0
            },
            methods: {
                search: function() {
                    this.current = 1;
                    this.loadRecords();
                },
                removeRecord: function(id) {
                    this.$confirm('确定删除该记录?')
                        .then(() => {
                            axios.delete(`/logs/proxy/${id}`)
                                .then(() => {
                                    this.loadRecords();
                                    this.$message.success('删除成功!');
                                })
                                .catch(() => {
                                    this.$message.error('删除失败!');
                                });
                        })
                        .catch(() => {});
                },
                changePage: function(page) {
                    this.current = page;
                    this.loadRecords();
                },
                loadRecords: function() {
                    axios.get('/logs/proxy', {
                            params: {
                                keyword: this.keyword,
                                offset: (this.current - 1) * this.pageSize,
                                limit: this.pageSize
                            }
                        })
                        .then(res => {
                            this.records = res.data.rows;
                            this.total = res.data.count;
                        })
                        .catch(err => console.error(err));
                }
            },
            mounted: function() {
                this.loadRecords();
            }
        });
    </script>
</body>
</html>

那么之后的话,这个简单的代理转发服务器就写好了。强行加上一层,服了。

以上就是Express代理转发服务器实现的详细内容,更多关于Express代理转发服务器的资料请关注其它相关文章!

返回顶部
顶部