Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
adding Access-Control-Allow-Origin header
Dear All;
with TIdHTTPServer, how do I add the "Access-Control-Allow-Origin" header?
My intuitive move with VCL was:
TIdHTTPServer *IdHTTPServer;
void __fastcall
TForm1::IdHTTPServerHeadersAvailable(TIdContext *AContext, const UnicodeString AUri,
          TIdHeaderList *AHeaders, bool &VContinueProcessing)
  AHeaders->Add("Access-Control-Allow-Origin: *");
  VContinueProcessing = true;
but when I test it with simple HTML in web browser:
    <BUTTON onclick="myFunction()" type="button">TEST</BUTTON>
      function myFunction(){
        let o = new XMLHttpRequest();
        //the IdHTTPServer is bound to """GET", "", false);
        o.send();//No 'Access-Control-Allow-Origin' header is present ...
browser throws "No 'Access-Control-Allow-Origin' header is present...". The TIdHTTPServer server does get this request with no complains of any kind.
BTW, if I insert my URL "" into the browser's address bar and press Enter - everyone is happy even if the server does not add an extra header.
(08-20-2022, 04:37 AM)Boba TC Wrote: with TIdHTTPServer, how do I add the "Access-Control-Allow-Origin" header?

"Access-Control-Allow-Origin" is a RESPONSE header, but you are adding it to the client's REQUEST headers instead. The server's OnHeadersAvailable event is meant for notifying your server code when the client's REQUEST headers have been received, so your server code can make a decision about whether to accept the request before the request's body is received and an OnCommand... event is fired to process the request.

(08-20-2022, 04:37 AM)Boba TC Wrote: My intuitive move with VCL was:

Unfortunately, your intuition was incorrect. The correct way to handle this situation is to add the "Access-Control-Allow-Origin" header to the AResponseInfo object provided in the OnCommand... events, for example:

void __fastcall TForm1::IdHTTPServerCommandGet(TIdContext *AContext,
    TIdHTTPRequestInfo *ARequestInfo, TIdHTTPResponseInfo *AResponseInfo)
    AResponseInfo->CustomHeaders->Add(_D("Access-Control-Allow-Origin: *"));
    // alternatively:
    // AResponseInfo->CustomHeaders->AddValue(_D("Access-Control-Allow-Origin"), _D("*"));
    // AResponseInfo->CustomHeaders->Values[_D("Access-Control-Allow-Origin")] = _D("*");

(08-20-2022, 04:37 AM)Boba TC Wrote: but when I test it with simple HTML in web browser:
browser throws "No 'Access-Control-Allow-Origin' header is present...".

Because it is looking for the header in the server's response, which is not where you are putting it.

Many thanks, Remy; will test it soon.

Works as expected!

Sorry for the late reply.  .Boba.

Forum Jump:

Users browsing this thread: 1 Guest(s)