Prolog 中的 CORS 不起作用

CORS in Prolog not work

我在 prolog 中遇到了 cors 问题。我认为它不起作用。

编辑#1

:- module(server,[]).

:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
:- use_module(library(http/http_cors)).
:- use_module(library(http/http_json)).
:- use_module(library(http/json_convert)).
:- use_module(library(option)).
:- use_module(library(settings)).
:- http_handler(root(.),handle,[]).

:- set_setting(http:cors, [*]).
server(Port) :-
   http_server(http_dispatch,[port(Port)]).

:- json_object
        poke(pokemon:text, move:text).
handle(Request) :-
   format(user_output,"Request is: ~p~n",[Request]),
   format(user_output,"Request2 is: ~p~n",[]),
   cors_enable,
   http_read_json_dict(Request, DictIn,[json_object(term)]),
   format(user_output,"I'm here~n",[]),
   term_string(Pokemon,DictIn.pokemon),
   findall(poke(P,M),beat(P,M,Pokemon),L),
   prolog_to_json(L,J),
   format(user_output,"Pokemons are: ~p~n",[J]),
   DictOut=J,
   reply_json(DictOut).

beat(P,M,E) :-
   pokerule:beat(P,M,E).

但是我使用 ajax post 来启动它说的服务器

XMLHttpRequest cannot load http://localhost:9999/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:1000' is therefore not allowed access. The response had HTTP status code 500.

Ajax 我用来 post.

   let enemyName = this.item.text
   let data = {"pokemon":enemyName}
   $.ajax({
     url        : END_POINT,
     method     : 'post',
     contentType: 'application/json',
     dataType   : 'json',
     data       : JSON.stringify(data),
     success    : function (res) {
       console.log(res);
     },
     error :function (res) {
       console.log(res);
     } 
   })

我该如何解决这个问题?

-已编辑 现在我修复了一些代码,但它仍然无法正常工作。

引用自 library(http/http_cors)documentation

Because CORS is a security risc (see references), it is disabled by default. It is enabled through the setting http:cors. The value of this setting is a list of domains that are allowed to access the service. Because * is used as a wildcard match, the value [*] allows access from anywhere.

(强调我的。)

因此,在您的服务器中,您可能必须包含以下设置:

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

默认情况下,cors_enable/0编写。

下次,请构建一个其他人可以实际尝试的最小示例。

编辑:您编辑的代码存在基本问题,这些问题与 CORS 无关。请将其缩减为 最小 示例。您可以通过以下方式查看问题所在:

  1. ?- server(4050). 启动服务器(例如)
  2. 正在您的网络浏览器中访问 http://localhost:4050

您将看到指示问题的错误消息。

这是 handle/2 的一个小框架,您可以根据需要对其进行扩展:

handle(Request) :-
        cors_enable,
        reply_json(test{x: 1, y: 2}).

我能以某种方式识别问题,这是由于浏览器发送的请求 header。它向 prolog 服务器发送 application/x-www-form-urlencoded; charset=UTF-8,这使得服务器在 http_json.pl 中的 is_json_type(String) 处失败。快速修复是将以下行插入谓词:

is_json_type(String) :-

String = 'application/x-www-form-urlencoded; charset=UTF-8', !.

你最好也把javascript下面一行去掉:

contentType: 'application/json'

因为还没有被服务器识别。我建议只使用标签、类型、数据类型、url 和 javascript 中的数据将这些参数传递给服务器。

我发现很难预测浏览器的请求包含什么,因为它取决于浏览器。因此,我认为,考虑到从浏览器发送的每一项可能的信息,将 prolog 程序保持最新是一项艰巨的工作。当服务器无法完成任务时,您最好检查请求中包含哪些项目。