eidheim / Simple-Web-Server

A very simple, fast, multithreaded, platform independent HTTP and HTTPS server and client library implemented using C++11 and Boost.Asio. Created to be an easy way to make REST resources available from C++ applications.
MIT License
2.61k stars 751 forks source link

Handling CORS Requests #196

Closed pacarvalho closed 6 years ago

pacarvalho commented 6 years ago

I looked over the code and documentation and was unable to find suggestions on how to handle Cross Origin Domain requests.

If I am serving my HTML from another server (same IP but different port) how can I handle CORS requests that will be made to the API server?

sebt3 commented 6 years ago

CORS is just an header. handle it like any http headers like it is done here : https://github.com/eidheim/Simple-Web-Server/blob/master/http_examples.cpp#L66 EDIT: I would strongly advice against using "*" as a value for this parameter

pacarvalho commented 6 years ago

Thank you.

I created a default PATH for the OPTIONS request and added the appropriate headers on the response of my other requests.

// Deals with CORS requests
server.default_resource["OPTIONS"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
  try {

      // Set header fields
      SimpleWeb::CaseInsensitiveMultimap header;
      header.emplace("Content-Type", "text/plain");
      header.emplace("Access-Control-Allow-Origin", "*");
      header.emplace("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
      header.emplace("Access-Control-Max-Age", "1728000");
      header.emplace("Access-Control-Allow-Headers", "authorization,content-type");

      response->write(SimpleWeb::StatusCode::success_ok, "", header);

  }
  catch(const exception &e) {
      response->write(SimpleWeb::StatusCode::client_error_bad_request, e.what());
  }
};