I am running an HTTP server with web::http::experimental::listener::http_listener from Microsoft C++ REST SDK 1.3.1 and try to write HTML&Javascript as a client to interact with the server.
almost without surprise I got ... Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ...... (Reason: CORS header 'Access-Control-Allow-Origin' missing).
How can I put Access-Control-Allow-Origin:* on the http listener side (in c++ code)??
Is it possible in C++ REST 1.3.1?? is there workaround except JSONP?
Server
#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);
}
Client Client with jQuery v1.12.4 (bounded to jQuery UI v1.12.0)
$("button").click(function () {
$.get(rest_url, function(data, status){
console.log(status);
console.log(data);
});
});
----------------- UPDATE -----------------------
Solution from the answer
SERVER
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);
}
CLIENT
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!');
}
}
});