1

I tried to implement HTTP server with cpp-netlib. Actually I could succeed to create a simple http server. But now I don't know how to set Access-Control-Allow-Origin option to my server.

This problem was found when I tried to access this server via a jQuery client. When I tried to access this server, it returns error like below. The server is running in different network.

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

So how do I set "Access-Control-Allow-Origin: *" in this code? I surveyed cpp-netlib document, but no information was founded.

Environment:

  • Visual Studio 2010 Professional 32bit
  • boost 1.54.0
  • cpp-netlib 0.9.4

My code:

#include <boost/network/protocol/http/server.hpp>
#include <iostream>

namespace http = boost::network::http;

struct hello_world;
typedef http::server<hello_world> server;

struct hello_world {
    void operator() (server::request const &request,
                     server::response &response) {
        server::string_type ip = source(request);
        std::ostringstream data;
        data << "Hello, " << ip << "!";
        response = server::response::stock_reply(
            server::response::ok, data.str());
    }
    void log(...) {
        // do nothing
    }
};


int main(int argc, char * argv[]) {

    if (argc != 3) {
        std::cerr << "Usage: " << argv[0] << " address port" << std::endl;
        return 1;
    }

    try {
        /*<< Creates the request handler. >>*/
        hello_world handler;
        /*<< Creates the server. >>*/
        server server_(argv[1], argv[2], handler);
        //server server_("127.0.0.1", 12344, handler);
        /*<< Runs the server. >>*/
        server_.run();
    }
    catch (std::exception &e) {
        std::cerr << e.what() << std::endl;
        return 1;
    }

    return 0;
}
jef
  • 3,890
  • 10
  • 42
  • 76

1 Answers1

2

This question is a few months old but I found myself working with cpp-netlib and had to do the same. So I thought I would answer for anyone else that comes across this question:

Access-Control-Allow-Origin needs to be set in the return header. So in your request handler you will need to set your response headers yourself(haven't tested code below but the gist is there):

response = server::response::stock_reply(
        server::response::ok, data.str());

server::response_header cors_header;
cors_header.name = "Access-Control-Allow-Origin";
cors_header.value = "*"; // "*" meaning allow any other server;

response.headers.push_back(cors_header);

Hope this helps.