Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
adding Access-Control-Allow-Origin header
#2
(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:

Code:
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.

Reply


Messages In This Thread
RE: adding Access-Control-Allow-Origin header - by rlebeau - 08-22-2022, 02:28 AM

Forum Jump:


Users browsing this thread: 1 Guest(s)