Skip to content

Commit

Permalink
Merge pull request #978 from bugdea1er/cors
Browse files Browse the repository at this point in the history
Add an option to expose headers for CORS
  • Loading branch information
gittiver authored Jan 7, 2025
2 parents 8dff896 + 0c33f5d commit 77eda0d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
18 changes: 18 additions & 0 deletions include/crow/middlewares/cors.h
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,22 @@ namespace crow
return *this;
}

/// Set Access-Control-Expose-Headers. Default is none
CORSRules& expose(const std::string& header)
{
add_list_item(exposed_headers_, header);
return *this;
}

/// Set Access-Control-Expose-Headers. Default is none
template<typename... Headers>
CORSRules& expose(const std::string& header, Headers... header_list)
{
add_list_item(exposed_headers_, header);
expose(header_list...);
return *this;
}

/// Set Access-Control-Max-Age. Default is none
CORSRules& max_age(int max_age)
{
Expand Down Expand Up @@ -108,6 +124,7 @@ namespace crow
set_header_no_override("Access-Control-Allow-Origin", origin_, res);
set_header_no_override("Access-Control-Allow-Methods", methods_, res);
set_header_no_override("Access-Control-Allow-Headers", headers_, res);
set_header_no_override("Access-Control-Expose-Headers", exposed_headers_, res);
set_header_no_override("Access-Control-Max-Age", max_age_, res);
if (allow_credentials_) set_header_no_override("Access-Control-Allow-Credentials", "true", res);
}
Expand All @@ -117,6 +134,7 @@ namespace crow
std::string origin_ = "*";
std::string methods_ = "*";
std::string headers_ = "*";
std::string exposed_headers_;
std::string max_age_;
bool allow_credentials_ = false;

Expand Down
12 changes: 11 additions & 1 deletion tests/unittest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1930,14 +1930,15 @@ TEST_CASE("middleware_cookieparser_format")

TEST_CASE("middleware_cors")
{

App<crow::CORSHandler> app;

auto& cors = app.get_middleware<crow::CORSHandler>();
// clang-format off
cors
.prefix("/origin")
.origin("test.test")
.prefix("/expose")
.expose("exposed-header")
.prefix("/nocors")
.ignore();
// clang-format on
Expand All @@ -1952,6 +1953,11 @@ TEST_CASE("middleware_cors")
return "-";
});

CROW_ROUTE(app, "/expose")
([&](const request&) {
return "-";
});

CROW_ROUTE(app, "/nocors/path")
([&](const request&) {
return "-";
Expand All @@ -1973,6 +1979,10 @@ TEST_CASE("middleware_cors")
"GET /origin\r\n\r\n");
CHECK(resp.find("Access-Control-Allow-Origin: test.test") != std::string::npos);

resp = HttpClient::request(LOCALHOST_ADDRESS, port,
"GET /expose\r\n\r\n");
CHECK(resp.find("Access-Control-Expose-Headers: exposed-header") != std::string::npos);

resp = HttpClient::request(LOCALHOST_ADDRESS, port,
"GET /nocors/path\r\n\r\n");

Expand Down

0 comments on commit 77eda0d

Please sign in to comment.