uNetworking / uWebSockets

Simple, secure & standards compliant web server for the most demanding of applications
Apache License 2.0
17.29k stars 1.75k forks source link

Unable to fail a request without triggering a CORS error #1754

Closed sgoth closed 3 months ago

sgoth commented 4 months ago

Is there a way to fulfill CORS correctly and still fail the request later on? For example encountering processing errors or input validation errors.

Calling this route from a browser results in a 200: Calling it without the CORS headers results in a fetch exception instead of an error.

.get("/error",[](uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
    res->writeHeader("Access-Control-Allow-Origin", "*");
    res->writeHeader("Access-Control-Allow-Credentials", "true");
    res->writeHeader("Access-Control-Allow-Headers", "authorization");
        res->writeStatus("400 Bad request");
        res->end(R"({ "error": "Some body" })");
})

Would be helpful to have a writeHeader without implicit writeStatus - or is there a reason against that?

uNetworkingAB commented 4 months ago

You need to move writeStatus before the writeHeader

sgoth commented 3 months ago

Ah ok that does work, thanks!

Still it would be nice if i could just write the CORS headers and then jump into the actual route handlers without knowing their return code in advance. But i guess it can also be done on every way out of the processing.

Is there a technical reason against a "writeHeaderOnly" function?

uNetworkingAB commented 3 months ago

status comes before headers so unless you have written status, first writeHeader will

sgoth commented 3 months ago

Right, sure status has to be first on the wire... Thanks for educating me and sorry for the noise :)

uNetworkingAB commented 3 months ago

Its a trade off. It could be more user friendly but then it wouldn't be as simple to run