2024年6月20日12:21:11
在main.cc里加入
/**
* 全局异常处理
*/
drogon::app().setExceptionHandler([](
const std::exception &e,
const drogon::HttpRequestPtr &req,
std::function<void(drogon::HttpResponsePtr &)> &&callback)
{
LOG_DEBUG << e.what();
Json::Value json;
json["code"] = FAIL;
json["error"] = e.what();
json["data"] = "";
auto resp = drogon::HttpResponse::newHttpJsonResponse(json);
callback(resp); });
// 跨域
drogon::app().registerSyncAdvice([](const drogon::HttpRequestPtr &req) -> drogon::HttpResponsePtr
{
if(req->method() == drogon::HttpMethod::Options)
{
auto resp = drogon::HttpResponse::newHttpResponse();
{
const auto& val = req->getHeader("Origin");
if(!val.empty())
resp->addHeader("Access-Control-Allow-Origin", val);
}
{
const auto& val = req->getHeader("Access-Control-Request-Method");
if(!val.empty())
resp->addHeader("Access-Control-Allow-Methods", val);
}
resp->addHeader("Access-Control-Allow-Credentials", "true");
{
const auto& val = req->getHeader("Access-Control-Request-Headers");
if(!val.empty())
resp->addHeader("Access-Control-Allow-Headers", val);
}
return std::move(resp);
}
return {}; })
.registerPostHandlingAdvice([](const drogon::HttpRequestPtr &req, const drogon::HttpResponsePtr &resp) -> void
{
{
const auto& val = req->getHeader("Origin");
if(!val.empty())
resp->addHeader("Access-Control-Allow-Origin", val);
}
{
const auto& val = req->getHeader("Access-Control-Request-Method");
if(!val.empty())
resp->addHeader("Access-Control-Allow-Methods", val);
}
resp->addHeader("Access-Control-Allow-Credentials", "true");
{
const auto& val = req->getHeader("Access-Control-Request-Headers");
if(!val.empty())
resp->addHeader("Access-Control-Allow-Headers", val);
} })
.run();
刚开始只写了 registerPostHandlingAdvice的处理发下不行,然后参看看
https://github.com/drogonframework/drogon/issues/2014
发现还要增加 registerSyncAdvice去单独处理 Options,才行,如果你在nginx做了跨域处理,还是不行的,本地测试还是有跨域问题
标签:Control,const,跨域,val,resp,Access,全局,drogon From: https://www.cnblogs.com/zx-admin/p/18258434