修改HTTP LIBRARY,增加OPTIONS支持

修改GATEWAY,修复转发
修改dnfs,暂时不编译(找不到模板)
修改static,能够获取节点
This commit is contained in:
qing committed 2026-07-22 12:47:13 +08:00
1 parent d60fe533bd
commit 419ae82858
8 files changed
+310 -23

No files matched your search

+4 -3
View File
@@ -1,5 +1,6 @@
#!/bin/bash
cd "$(dirname "$0")" || exit
#bash ./_setup.sh
#source ./.env/bin/activate
exec ./dnfs.bin
bash ./_setup.sh
source ./.env/bin/activate
#exec ./dnfs.bin
exec python3 dnfs.py
+144
View File
@@ -0,0 +1,144 @@
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>树状笔记</title>
<!-- ​Font Awesome 6.0.0 是矢量图标库,提供 7,000+ 免费图标及 17,000+ 专业图标。 -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
<!-- 外部CSS文件 -->
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<div class="container">
<div class="header">
<h1><i class="fas fa-sitemap"></i> 树状笔记</h1>
<div class="header-actions">
<button onclick="resetForm()" class="btn btn-primary"><i class="fas fa-plus"></i> 新增节点</button>
<button onclick="goBack()" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> 返回上级</button>
</div>
</div>
<!-- 节点迁移模式提示栏 -->
<div id="move-mode-bar" class="move-mode-bar" style="display: none;">
<div class="move-mode-info">
<i class="fas fa-exchange-alt"></i>
正在迁移节点:<strong id="moving-node-title"></strong>
</div>
<div class="move-mode-actions">
<button onclick="confirmMoveHere()" class="btn btn-move-here"><i class="fas fa-arrow-down"></i> 移动到此</button>
<button onclick="cancelMove()" class="btn btn-cancel-move"><i class="fas fa-times"></i> 取消</button>
</div>
</div>
<div class="main-content">
<div class="form-section">
<!-- 表单标题 -->
<h3 class="form-title"><i class="fas fa-pen"></i> <span id="form-mode-text">新增节点</span></h3>
<input type="hidden" id="edit-id" value=""> <!-- 隐藏输入框,要编辑节点的id -->
<!-- 输入节点标题 -->
<div class="form-group">
<label for="node-title"><i class="fas fa-heading"></i> 标题</label>
<input type="text" id="node-title" class="form-control" placeholder="输入节点标题">
</div>
<!-- 输入节点内容 -->
<div class="form-group">
<label for="node-content"><i class="fas fa-file-alt"></i> 节点说明</label>
<textarea id="node-content" class="form-control" placeholder="输入节点的文字说明"></textarea>
</div>
<!-- 文件上传区域 -->
<div class="form-group">
<label><i class="fas fa-upload"></i> 文件上传</label>
<div class="file-upload-area" onclick="document.getElementById('file-upload').click()">
<i class="fas fa-cloud-upload-alt" style="font-size: 2em; color: #888; margin-bottom: 10px;"></i>
<p>点击或拖拽文件到此处上传</p>
<p style="font-size: 0.8em; color: #999;">文件将以编码形式保存,同一节点内数据不要超过1M</p>
<input type="file" id="file-upload" style="display: none;" onchange="handleFileUpload(this.files)"> <!-- 隐藏输入框 -->
</div>
<!-- 选择文件状态信息 -->
<div class="file-info" id="file-info">未选择文件</div>
<!-- 文件元信息显示 -->
<div id="file-meta-container" style="display: none;">
<div id="file-meta-info" class="file-meta-info">
<p><i class="fas fa-file"></i> 文件名:<span id="meta-filename"></span></p>
<p><i class="fas fa-hdd"></i> 文件大小:<span id="meta-filesize"></span></p>
<p><i class="fas fa-calendar-alt"></i> 上传时间:<span id="meta-uploadtime"></span></p>
</div>
</div>
<!-- 数据修复提示 -->
<div id="data-repair-hint" class="data-repair-hint" style="display: none;">
<i class="fas fa-exclamation-circle"></i>
<span>检测到文件元数据损坏。请尝试重新上传文件以修复此问题。</span>
</div>
<!-- 文件进度条 -->
<div class="file-progress">
<div class="file-progress-bar" id="file-progress-bar"></div>
</div>
</div>
<!-- 文件下载区域(仅在有文件时显示) -->
<div class="form-group" id="download-section" style="display: none;">
<label><i class="fas fa-download"></i> 文件操作</label>
<div style="display: flex; gap: 8px;">
<button onclick="decodeAndDownload(null, null, true)" class="btn btn-success">
<i class="fas fa-download"></i> 下载文件
</button>
<button onclick="removeFile()" class="btn btn-danger">
<i class="fas fa-trash"></i> 移除文件
</button>
</div>
</div>
<!-- 隐藏的Base64存储字段 - 用户永远不会看到 -->
<textarea id="hidden-base64" class="form-control hidden-field" placeholder="Base64编码内容(自动生成,隐藏显示)"></textarea>
<input type="hidden" id="file-metadata" value="">
<!-- 动作表单 -->
<div class="form-actions">
<button onclick="saveNode()" class="btn btn-primary"><i class="fas fa-save"></i> 保存</button>
<button onclick="resetForm()" class="btn btn-secondary"><i class="fas fa-undo"></i> 重置</button>
</div>
</div>
<!-- 节点表单 -->
<div id="node-list" class="node-list">
<div class="loading"><i class="fas fa-spinner"></i><p>加载中...</p></div>
</div>
</div>
</div>
<!-- 删除确认模态框 -->
<div id="delete-modal" class="modal">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title"><i class="fas fa-exclamation-triangle"></i> 确认删除</h3>
<button class="modal-close" onclick="closeDeleteModal()"><i class="fas fa-times"></i></button>
</div>
<div class="modal-body">
<p id="delete-message">确定删除该节点吗?</p>
<p id="delete-node-title-container" style="font-weight: bold; margin: 8px 0;"></p>
<p id="delete-file-hint" style="font-size:.85em;color:#e74c3c;display:none;"><i class="fas fa-exclamation-circle"></i> 此节点包含文件,删除后文件将无法恢复</p>
<p style="font-size:.85em;color:#777">此操作不可恢复</p>
</div>
<div class="modal-footer">
<button onclick="confirmDelete()" class="btn btn-danger"><i class="fas fa-trash"></i> 删除</button>
<button onclick="closeDeleteModal()" class="btn btn-secondary"><i class="fas fa-times"></i> 取消</button>
</div>
</div>
</div>
<div id="toast-container"></div>
<!-- 外部JS文件 -->
<script src="{{ url_for('static', filename='js/script.js') }}"></script>
</body>
</html>
+27 -14
View File
@@ -273,6 +273,19 @@ void registerRoutes(HttpServer &server) {
server.post("*", [](const auto& req, const auto& params) {
return handleProxy(req, params, "post");
});
server.options("*", [](const auto& req, const auto& params) {
pmc::net::http::response<pmc::net::http::string_body> res;
res.result(pmc::net::http::status::ok);
res.set(pmc::net::http::field::access_control_allow_origin, "*");
res.set(pmc::net::http::field::access_control_allow_methods, "GET, POST, OPTIONS");
res.set(pmc::net::http::field::access_control_allow_headers, "Content-Type, Authorization");
res.set(pmc::net::http::field::access_control_max_age, "86400");
res.body() = "";
res.content_length(0);
res.prepare_payload();
return res;
});
}
http::response<http::string_body> wrapperHttp(
@@ -444,6 +457,7 @@ http::response<http::string_body> handleProxy(
std::string t_url = "";
std::string url = "";
std::string auth = "";
json::value jv_t; /* json value of the token */
{
auto flag = false;
auto it = req.base().find("Target-Url");
@@ -456,7 +470,7 @@ http::response<http::string_body> handleProxy(
t_url = req["target-url"];
}
if (url == "") {
if (t_url == "") {
t_url = _DEFT_URL;
flag = true;
}
@@ -466,7 +480,7 @@ http::response<http::string_body> handleProxy(
url += req.target();
it = req.base().find("Authorization");
if (it == req.base().end() && !flag) {
if (it == req.base().end() && !flag) { /* 不是默认代理地址且无令牌 */
throw std::runtime_error("401");
}
std::string raw = req["Authorization"];
@@ -484,21 +498,20 @@ http::response<http::string_body> handleProxy(
}
std::cout << "auth data: " << auth << std::endl;
}
}
json::value jv;
/* 令牌是否过期 */
{
/* TODO: 放进try包裹 */
jv = json::parse(auth);
json::object& obj = jv.as_object();
if (!flag) { /* 令牌是否过期 */
/* TODO: 放进try包裹 */
jv_t = json::parse(auth);
json::object& obj = jv_t.as_object();
auto t = json::value_to<std::string>(obj["created_at"]);
bool r = LocalTime::isExpired(t);
auto t = json::value_to<std::string>(obj["created_at"]);
bool r = LocalTime::isExpired(t);
if (r) {
THROW_EX_CUSTOM(HttpException, 2000, "Authorization Expired",
401, "*");
if (!r) {
THROW_EX_CUSTOM(HttpException, 2000, "Authorization Expired",
401, "*");
}
}
}
+3
View File
@@ -60,6 +60,7 @@ public:
void post(const std::string& path, HttpRequestHandler handler);
void put(const std::string& path, HttpRequestHandler handler);
void del(const std::string& path, HttpRequestHandler handler);
void options(const std::string& path, HttpRequestHandler handler); // 新增 OPTIONS
void use(MiddlewareHandler middleware);
void setStaticDirectory(const std::string& path);
@@ -102,6 +103,7 @@ private:
std::vector<RouteEntry> post_handlers_;
std::vector<RouteEntry> put_handlers_;
std::vector<RouteEntry> delete_handlers_;
std::vector<RouteEntry> options_handlers_; // 新增 OPTIONS 路由
std::vector<MiddlewareHandler> middlewares_;
std::string static_directory_;
@@ -113,6 +115,7 @@ private:
bool matchPath(const std::string& path, const std::regex& pattern);
http::response<http::string_body> handleRequest(const http::request<http::string_body>& req);
HttpRequestHandler findRoute(const std::string& method, const std::string& path);
bool routeExists(const std::string& method, const std::string& path); // 新增辅助方法
void addSession(const std::shared_ptr<Session>& session);
void removeSession(const Session* session);
+83 -4
View File
@@ -4,7 +4,7 @@
#include <sstream>
#include <iomanip>
#include <openssl/err.h>
#include <openssl/ssl.h> // SSL_CTX_set_cipher_list
#include <openssl/ssl.h>
namespace pmc {
namespace net {
@@ -85,7 +85,6 @@ private:
<< remote_ip_ << ":" << remote_port_
<< " - " << ec.message()
<< " (code=" << ec.value() << ")" << std::endl;
// 输出 OpenSSL 详细错误堆栈
ERR_print_errors_fp(stderr);
}
}));
@@ -168,7 +167,6 @@ private:
HttpServer* server_;
bool ssl_enabled_;
// 使用 any_io_executor 兼容多种执行器
asio::strand<asio::any_io_executor> strand_;
std::string remote_ip_ = "unknown";
@@ -272,7 +270,6 @@ void HttpServer::initSSLContext() {
asio::ssl::context::no_sslv3 |
asio::ssl::context::single_dh_use);
// 设置现代加密套件,确保兼容主流客户端
SSL_CTX_set_cipher_list(ssl_ctx_->native_handle(),
"ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20:!aNULL:!MD5:!DSS");
@@ -391,6 +388,17 @@ void HttpServer::del(const std::string& path, HttpRequestHandler handler) {
delete_handlers_.push_back(entry);
}
// ---- 新增 OPTIONS 路由注册 ----
void HttpServer::options(const std::string& path, HttpRequestHandler handler) {
RouteEntry entry;
entry.path = path;
entry.handler = handler;
entry.is_wildcard = (path.find('*') != std::string::npos ||
path.find('?') != std::string::npos);
if (entry.is_wildcard) entry.pattern = wildcardToRegex(path);
options_handlers_.push_back(entry);
}
void HttpServer::use(MiddlewareHandler m) {
middlewares_.push_back(m);
}
@@ -442,6 +450,7 @@ HttpRequestHandler HttpServer::findRoute(const std::string& method, const std::s
else if (method == "POST") handlers = &post_handlers_;
else if (method == "PUT") handlers = &put_handlers_;
else if (method == "DELETE") handlers = &delete_handlers_;
else if (method == "OPTIONS") handlers = &options_handlers_;
else return nullptr;
// 精确匹配优先
@@ -455,6 +464,11 @@ HttpRequestHandler HttpServer::findRoute(const std::string& method, const std::s
return nullptr;
}
// ---- 新增辅助方法:检查路由是否存在 ----
bool HttpServer::routeExists(const std::string& method, const std::string& path) {
return findRoute(method, path) != nullptr;
}
// ---- 请求处理核心 ----
http::response<http::string_body> HttpServer::handleRequest(const http::request<http::string_body>& req) {
std::string target_path(req.target().data(), req.target().size());
@@ -486,6 +500,68 @@ http::response<http::string_body> HttpServer::handleRequest(const http::request<
}
std::string method = http::to_string(req.method());
// ========== 处理 OPTIONS 预检请求 ==========
if (method == "OPTIONS") {
// 检查是否有自定义 OPTIONS 路由
auto handler = findRoute("OPTIONS", target_path);
if (handler) {
try {
return handler(req, params);
} catch (const std::exception& e) {
std::cerr << "[Handler] Exception: " << e.what() << std::endl;
res.result(http::status::internal_server_error);
res.body() = "500 Internal Server Error\n";
res.prepare_payload();
return res;
}
}
// 自动生成 OPTIONS 响应
auto origin = req.find(http::field::origin);
if (origin != req.end()) {
// 构建允许的方法列表
std::vector<std::string> all_methods = {"GET", "POST", "PUT", "DELETE", "OPTIONS"};
std::vector<std::string> allowed_methods;
// 检查每个方法是否有对应的路由
for (const auto& m : all_methods) {
if (m == "OPTIONS" || routeExists(m, target_path)) {
allowed_methods.push_back(m);
}
}
if (!allowed_methods.empty()) {
std::string allow_methods;
for (size_t i = 0; i < allowed_methods.size(); ++i) {
if (i > 0) allow_methods += ", ";
allow_methods += allowed_methods[i];
}
res.result(http::status::ok);
res.set(http::field::allow, allow_methods);
res.set(http::field::access_control_allow_origin,
std::string(origin->value()));
res.set(http::field::access_control_allow_methods, allow_methods);
res.set(http::field::access_control_allow_headers,
"Content-Type, Authorization, X-Requested-With, Accept, Origin");
res.set(http::field::access_control_max_age, "86400");
res.body() = "";
res.content_length(0);
res.prepare_payload();
return res;
}
}
// 没有 Origin 头或没有匹配的方法
res.result(http::status::not_found);
res.body() = "404 Not Found\n";
res.prepare_payload();
return res;
}
// ========== OPTIONS 处理结束 ==========
// 查找普通路由
auto handler = findRoute(method, target_path);
// 静态文件
@@ -562,6 +638,9 @@ void HttpServer::showStatus() const {
std::cout << " DELETE: " << delete_handlers_.size() << " handler(s)" << std::endl;
for (const auto& entry : delete_handlers_)
std::cout << " DELETE " << entry.path << (entry.is_wildcard ? " (wildcard)" : "") << std::endl;
std::cout << " OPTIONS: " << options_handlers_.size() << " handler(s)" << std::endl; // 新增
for (const auto& entry : options_handlers_)
std::cout << " OPTIONS " << entry.path << (entry.is_wildcard ? " (wildcard)" : "") << std::endl;
std::cout << "Middlewares: " << middlewares_.size() << std::endl;
std::cout << "==========================" << std::endl;
}
+2 -1
View File
@@ -98,5 +98,6 @@
<li><a href="https://www.baidu.com">百度推荐</a></li>
</ul>
</div>
<script src="/js/dnfs.js"></script>
</body>
</html>
</html>
+46
View File
@@ -0,0 +1,46 @@
async function getNode(token, id) {
try {
obj = { "pid": String(id) }
jsonBody = JSON.stringify(obj)
alert(jsonBody)
const res = await fetch('/get_notes', {
method: 'POST',
headers: {
'Content-Type': 'application/json', // 告诉服务器内容为json
'Authorization': `Bearer ${token}`,
'Target-Url': 'http://127.0.0.1:8006'
},
body: jsonBody
});
const responseText = await res.text();
let result;
try {
result = JSON.parse(responseText);
} catch {
console.error(`登录接口返回非 JSON 内容(HTTP ${res.status}):`, responseText);
throw new Error('服务器响应格式异常,请稍后重试');
}
if (!res.ok) {
throw new Error(result.message || `获取节点失败(HTTP ${res.status})`);
}
//if (result.success) {
alert(`获取节点成功`);
//...
//} else {
// alert(result.message || '获取节点失败');
//}
} catch (err) {
alert(err.message || '接口请求失败,请检查后端服务是否启动');
console.error('登录请求异常:', err);
} finally {
}
}
var token = sessionStorage.getItem('q4_token')
var main_node = getNode(token, 0)
+1 -1
View File
@@ -148,7 +148,7 @@ form.addEventListener('submit', async function(e) {
if (result.success) {
alert(`登陆成功`);
sessionStorage.setItem('token', result.data.token);
sessionStorage.setItem('q4_token', result.data.token);
location.href = 'dnfs.html';
} else {
alert(result.message || '登录失败');