在c++ REST SDK中增加http_listener的Access-Control-Allow-Origin

add Access-Control-Allow-Origin on http_listener in C++ REST SDK

本文关键字:listener Access-Control-Allow-Origin http 增加 c++ REST SDK      更新时间:2023-10-16

我正在运行一个HTTP服务器web:: HTTP::experimental::listener::http_listener来自Microsoft c++ REST SDK 1.3.1,并尝试编写HTML&Javascript作为客户端与服务器交互。

毫无疑问,我得到了……跨域请求阻塞:同源策略不允许读取远程资源......(原因:CORS头'Access-Control-Allow-Origin'丢失).

我怎么能把Access-Control-Allow-Origin:*在http侦听器端(在c++代码)??

在c++ REST 1.3.1中可能吗??除了JSONP,还有其他解决方案吗?

服务器

#include <cpprest/http_listener.h>
#include <cpprest/json.h>
using namespace web;
using namespace web::http;
using namespace web::http::experimental::listener;
http_listener httpSrv;
httpSrv->support(methods::GET, handle_get);
void handle_get(http_request request)
{
  const json::value response;
  request.reply(status_codes::OK, response);
}

客户端使用jQuery v1.12.4的客户端(限定为jQuery UI v1.12.0)

    $("button").click(function () {
        $.get(rest_url, function(data, status){
            console.log(status);
            console.log(data);
        });
    });

----------------- 更新 -----------------------

答案解

服务器

  http_listener httpSrv;
  httpSrv.support(methods::GET, handle_get);
  httpSrv.support(methods::POST, handle_post);
  httpSrv.support(methods::OPTIONS, handle_options);
  httpSrv.open().wait();
  //...........
  void handle_options(http_request request)
  {
    http_response response(status_codes::OK);
    response.headers().add(U("Allow"), U("GET, POST, OPTIONS"));
    response.headers().add(U("Access-Control-Allow-Origin"), U("*"));
    response.headers().add(U("Access-Control-Allow-Methods"), U("GET, POST, OPTIONS"));
    response.headers().add(U("Access-Control-Allow-Headers"), U("Content-Type"));
    request.reply(response);
  }
  void handle_get(http_request request)
  {        
    request.reply(status_codes::OK, ...);
  }
  void handle_post(http_request request)
  {
    json::value jsonResponse;
    request
      .extract_json()
      .then([&jsonResponse](pplx::task<json::value> task)
      {
        jsonResponse = process_request(task.get());
      })
     .wait();
    http_response response(status_codes::OK);
    response.headers().add(U("Access-Control-Allow-Origin"), U("*"));
    response.set_body(jsonResponse);
    request.reply(response);
  }  
客户

  function requestREST(request/*json*/,onSuccess/*callback with json response*/) {    
    $.ajax({     
        type: "POST",
        url: "...",
        data: JSON.stringify(request),
        dataType: 'json',
        crossDomain: true,
        contentType: "application/json",
        success: function (response) {
            onSuccess(response);
        },
        timeout:3000,
        statusCode: {
            400: function (response) {
                alert('Not working!');
            },
            0: function (response) {
                alert('Not working!');
            }              
        }
    });

要在服务器端(c++)添加报头,您需要修改用于发送响应的代码。

此时,您正在使用:

request.reply(status_codes::OK, response);

与其在一行代码中这样做,不如自己编写响应,从一个空响应开始,添加所需的标头,设置实际的正文,然后将响应发送回客户端。

要构造空响应,可以使用以下函数:
web::http::http_response::http_response(http::status_code code)

如文档中所述,它将构造一个具有给定状态码的响应,没有头和正文。

要访问响应的报头,可以使用以下函数:

web::http::http_response::headers()

返回的对象将是包含add函数的http_headers类型:

web::http::http_headers::add(const key_type &name, const _t1 &value)

如果为响应提供了名称和值,该函数将为响应添加一个头。

设置header后,只剩下body了。要做到这一点,响应具有set_body函数:

web::http::http_response::set_body(const json::value &body_data)

最后,完整的代码替换您的一行代码来创建一个空响应,设置标题和正文,然后将其发送回来,如下所示:

http_response response(status_codes::OK);
response.headers().add(U("Access-Control-Allow-Origin"), U("*"));
response.set_body(jsonResponse);
request.reply(response);

请注意,在代码的最后一部分,我使用U宏来创建目标平台类型的字符串字面值。您可以在c++ Rest SDK FAQ中找到有关U宏的更多信息。

关于使用OPTION HTTP谓词的飞行前请求,这些在这种情况下是预期的。默认情况下,c++ REST SDK包含这些请求的默认实现。默认实现可以在源代码中检查:

void details::http_listener_impl::handle_options(http_request message)
{
    http_response response(status_codes::OK);
    response.headers().add(U("Allow"), get_supported_methods());
    message.reply(response);
}

它基本上是返回一个200状态码,并添加一个服务器可以处理的支持方法列表。

如果你想覆盖默认实现,例如添加一些特定的标题,如Access-Control-Allow-MethodsAccess-Control-Allow-Headers的飞行前请求使用,你需要添加一个特定的处理程序,就像你为GETPOST请求所做的那样:

web::http::experimental::listener::http_listener::support(const http::method &method, const std::function< void(http_request)> &handler)

不可能使用一般处理程序来处理OPTION请求:

web::http::experimental::listener::http_listener::support(const std::function<void(http_request)> &handler)

如果我们看一下源代码,我们不能使用通用处理程序的原因是,如果一个方法没有特定的处理程序,并且使用OPTION HTTP动词(或TRACE),那么c++ REST SDK实现的默认处理程序将被调用:

// Specific method handler takes priority over general.
const method &mtd = msg.method();
if(m_supported_methods.count(mtd))
{
    m_supported_methods[mtd](msg);
}
else if(mtd == methods::OPTIONS)
{
    handle_options(msg);
}