Skip to content
This repository was archived by the owner on Aug 2, 2020. It is now read-only.

Commit 5cb7454

Browse files
committed
Support CORS
1 parent fad61e9 commit 5cb7454

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

src/cqhttp/plugins/web/http.cpp

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,20 @@ namespace cqhttp::plugins {
3434
};
3535

3636
const auto action_path_regex = "^/([^/\\s]+)/?$";
37+
server_->resource[action_path_regex]["OPTIONS"] =
38+
[=](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
39+
log_request(request);
40+
if (enable_cors_) {
41+
response->write("",
42+
{
43+
{"Access-Control-Allow-Origin", "*"},
44+
{"Access-Control-Allow-Methods", "*"},
45+
{"Access-Control-Allow-Headers", "*"},
46+
});
47+
} else {
48+
response->write(SimpleWeb::StatusCode::client_error_method_not_allowed);
49+
}
50+
};
3751
server_->resource[action_path_regex]["GET"] = server_->resource[action_path_regex]["POST"] =
3852
[=](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
3953
log_request(request);
@@ -99,7 +113,8 @@ namespace cqhttp::plugins {
99113
response->write(SimpleWeb::StatusCode::client_error_not_found);
100114
} else {
101115
logging::debug(TAG, u8"动作 " + action + u8" 执行成功");
102-
const decltype(request->header) headers{{"Content-Type", "application/json; charset=UTF-8"}};
116+
decltype(request->header) headers{{"Content-Type", "application/json; charset=UTF-8"}};
117+
if (enable_cors_) headers.emplace("Access-Control-Allow-Origin", "*");
103118
const auto resp_body = json(result).dump();
104119
logging::debug(TAG, u8"响应数据已准备完毕:" + resp_body);
105120
response->write(resp_body, headers);
@@ -176,6 +191,7 @@ namespace cqhttp::plugins {
176191
use_http_ = ctx.config->get_bool("use_http", true);
177192
access_token_ = ctx.config->get_string("access_token", "");
178193
serve_data_files_ = ctx.config->get_bool("serve_data_files", false);
194+
enable_cors_ = ctx.config->get_bool("enable_cors", false);
179195

180196
if (use_http_) {
181197
init_server();

src/cqhttp/plugins/web/http.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ namespace cqhttp::plugins {
2626
bool use_http_{};
2727
std::string access_token_{};
2828
bool serve_data_files_{};
29+
bool enable_cors_{};
2930

3031
std::shared_ptr<SimpleWeb::Server<SimpleWeb::HTTP>> server_;
3132
std::thread thread_;

0 commit comments

Comments
 (0)