Problem with CORS

I’m using: SWI-Prolog version version 9.2.1 for x64-win64

I want to make an api but I’m having problems with cors
It works fine when I use postman but from an FE created with react I have problems with the CORS
This is my code:

:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
:- use_module(library(http/http_json)).
:- use_module(library(http/http_path)).
:- use_module(library(http/http_parameters)).
:- use_module(library(http/html_write)).
:- use_module(library(http/http_cors)).
:- set_setting(http:cors, [*]).

% URL handlers.
:- http_handler('/solve', handle_solve, [method(post)]).

handle_solve(Request) :-
    http_read_json_dict(Request, DictIn),
    Initial = DictIn.initial,
    Goal = DictIn.goal,
    transform_lists(Initial, L),
    transform_lists(Goal, G),
    solve(L, G, Response),
    count(Response, N),
    DictOut = _{moves: Response, quantity:N},

server(Port) :-
    http_server(http_dispatch, [port(Port)]).

:- initialization
    (current_prolog_flag(argv, [SPort | _]) -> true ; SPort='8000'),
    atom_number(SPort, Port),

Looks like get vs post:

From SWI-Prolog -- library(http/http_cors): Enable CORS: Cross-Origin Resource Sharing

    List of supported HTTP methods. The default is GET, only allowing for read requests.

So, I would try cors_enable/2

Sorry, can you give me an example of how to implement it? I honestly don’t know how

There’s an example in Battling with cors_enable

home_handler(Request) :-
  cors_enable(Request, [methods([get,post])]),

I tried it but it didn’t work

I had a similar problem, and after testing with a library in a different programing language (in my case node’s http-server) found the problem wasn’t SWI-Prolog related. So I’d suggest testing it with the equivalent library in Node, Python or whatever.
Most of these programming languages use the same underlying C-libraries, and CORS is a “universal problem”.

1 Like