express的代理转发
其实我的内心关于这个Express,我的内心是拒绝的,不是说,我对这个框架有什么看法,而是因为这个大作业的问题。是的我还是一个大三老菜鸡,苦练 Java 全干开发,Python 人工智能 整整 一坤年。期间拿了几个奖,水了篇论文 而已。
那么这篇文章主要做的,其实很简单就是,做个代理转发。前端请求,先到express服务器,然后转发到flask服务器,为什么非要转发呢,原因很简单,web作业非要用node平台,没办法,但是我的服务已经用flask做好了,当然这个和我先前写的那个微信聊天的不一样哈,这个是另一个,是视觉识别算法,说到这个,我本人目前也在手写一个全新的目标检测算法,希望可以起到不错的效果,扯远了。所以没有办法,只能做一个express的代理转发。
但是呢,为了体现工作量,我在这个转发服务器里面加了点东西:
就是这个,加点curd,不然不好混。
项目结构
这个的话,更像是一个dome,所以的话,项目结构非常简单。
因为核心功能就一个,就是做转发,然后呢,加上一些配套的记录就好了。
然后就是我们的数据库还有页面之类的。当然整个项目还是使用这个生成工具先生成了一个模板工程的。
由于整个项目简单,骨架也是生成的,所以我这边就只说,它的一些核心实现了。
转发
那么首先就是我们的核心,代理转发:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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当中去了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | 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里面去注册这些接口。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 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 就可以访问页面:
1 2 3 | app.get( '/logs' , (req, res) => { res.sendFile(__dirname + '/public/logs.html' ); }); |
对应的html代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | <title>代理日志查看</title> /* 设置全局字体和颜色 */ #app { margin: 0 auto; width: 80%; } <div id= "app" > <h1>代理日志</h1> 搜索{{ new Date(scope.row.createdAt).toLocaleString() }}删除 </div> 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(); } }); |
那么之后的话,这个简单的代理转发服务器就写好了。强行加上一层,服了。
以上就是Express代理转发服务器实现的详细内容,更多关于Express代理转发服务器的资料请关注IT俱乐部其它相关文章!