meltwater / served

A C++11 RESTful web server library
MIT License
710 stars 173 forks source link

how to add header Access-Control-Allow-Origin ? #66

Open blastbeng opened 4 years ago

blastbeng commented 4 years ago

Hi, I have the following error: "...has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

so i need to add the Access-Control-Allow-Origin header, actually I am using the json_data example

How to do that?

Thanks and Regards

kiyoMatsui commented 4 years ago

Hi blastbeng... CORS should not be disabled when using curl. I guess you are calling from a browser? If you could provide more info so I can reproduce it I'll have another look. I think in the end you should do something like res.set_header("Access-Control-Allow-Origin", "http://someurl.*"); or something like that...

shlomnissan commented 4 years ago

@blastbeng when I was trying to access the API directly from a browser my primary issue with CORS was the preflight request. I ended up wrapping my handlers with the following for the time being

mux.use_wrapper([](served::response & res, const served::request & req, const std::function<void()> & handler){
    res.set_header("Access-Control-Allow-Origin", "*");
    if (req.method() == served::method::OPTIONS) {
        res.set_header("Access-Control-Allow-Headers", "*");
        res.set_status(200);
    } else {
        handler();
    }
});