CORS error when requesting prolog webservice

I’m using: SWI-Prolog version 8.0.3 for x86_64-linux

I want the code to: To be able to receive requests from external applications.

But what I’m getting is: I get the “Access-Control-Allow-Origin not present on requested source” error when requesting my prolog webservice

My code looks like this:

:- use_module(library(http/http_cors)).
:- use_module(library(http/http_parameters)).
:- use_module(library(http/http_client)).
:- use_module(library(http/http_header)).
:- use_module(library(http/html_write)).
:- use_module(library(uri)).

:- set_setting(http:cors, [*]).

someurl("https://some.url").

:- http_handler('/test', test_predicate, []).

test_predicate(Request):-
  ((
    option(method(options), Request),!,cors_enable(Request,[methods([get,post,delete])]),format('~n')
  );(
  populateData,
  %additional code%
  format('Access-Control-Allow-Origin: *~n'),
  format('Content-type: application/json~n'), !)).

populateData:-
  add_Users(_).

addUsers(_Request):-
  cors_enable,
  obtainData(Data),
%some code%.

obtainData(Object):-
  someurl(URL),
  http_get(URL,Object,[]).

When I request the data from Postman everything works as expected so the problem must be in the way I use cors_enable. Basically, when the test_predicate runs it must execute the populateData predicate. Should I pass the Request parameter that I get in test_predicate to populateData? Is that the issue or am I missing a piece of code?

This is pretty hard to read, but you seem to send the CORS header twice and do not finish the header with a double newline. I’d use something like below. Using two clauses is a lot more readable than ;/2 with !-s.

test_predicate(Request) :-
    option(method(options), Request),
    !,
    cors_enable(Request,[methods([get,post,delete])]),
    format('Content-type: text/plain\r\n'),
    format('~n'). 
test_predicate(Request) :-
    cors_enable,
    reply_json(_{msg: "Hello world!"}).

So the issue was with the second request. I had to pass the Request variable to the populateData predicate and from there I had to pass it to addUser.

Like this:

test_predicate(Request):-
  ((
    option(method(options), Request),!,cors_enable(Request,[methods([get,post,delete])]),format('~n')
  );(
  populateData(Request),
  %additional code%
  format('Access-Control-Allow-Origin: *~n'),
  format('Content-type: application/json~n'), !)).

populateData(Request):-
  add_Users(Request).

addUsers(Request):-
  obtainData(Data),
%some code%.

This fixed the problem. As always thank you for your answer!!