我正在使用来自 Microsoft C++ REST SDK 1.3.1 的 web::http::experimental::listener::http_listener 运行 HTTP 服务器,并尝试编写 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!');
}
}
});