pistacheio / pistache

A high-performance REST toolkit written in C++
https://pistacheio.github.io/pistache/
Apache License 2.0
3.2k stars 700 forks source link

The parameter "Access-Control-Allow-Credentials" at server side #821

Open spartakrogov opened 4 years ago

spartakrogov commented 4 years ago

Hello guys,

Me need to add "Access-Control-Allow-Credentials" parameter to response ("Access-Control-Allow-Credentials : true") How I can set Access-Control-Allow-Credentials parameter in server side?

best regards, Spartak

ljluestc commented 3 days ago

#include <pistache/endpoint.h>
#include <pistache/http.h>
#include <pistache/router.h>
#include <iostream>

using namespace Pistache;

class CustomHandler : public Http::Handler {
public:
    HTTP_PROTOTYPE(CustomHandler)

    void onRequest(const Http::Request& request, Http::ResponseWriter response) override {
        // Log request information
        std::cout << "Request URL: " << request.resource() << std::endl;
        std::cout << "Request Method: " << request.method() << std::endl;
        std::cout << "Remote Address: " << request.remoteAddress().host() << std::endl;

        // Set CORS headers
        response.headers().add<Http::Header::AccessControlAllowOrigin>("*"); // Allow all origins
        response.headers().add<Http::Header::AccessControlAllowCredentials>("true"); // Allow credentials

        // Set Content-Type and send response
        response.headers().add<Http::Header::ContentType>(MIME(Text, Plain));
        response.send(Http::Code::Ok, "Hello, World!");
    }
};

int main() {
    // Create an HTTP server
    Port port(9080);
    int threads = 2;

    auto opts = Http::Endpoint::options()
                    .threads(threads);

    Http::Endpoint server(Address(Ipv4::any(), port));
    server.init(opts);

    // Set up the router
    Rest::Router router;
    Rest::Routes::Get(router, "/hello", Rest::Routes::bind(&CustomHandler::onRequest));

    server.setHandler(router.handler());

    // Start the server
    std::cout << "Starting server on port 9080..." << std::endl;
    server.serve();
    return 0;
}