我在序言中对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。

   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


由于CORS是一种安全风险(请参阅参考资料),因此默认情况下将其禁用。通过设置http:cors启用。此设置的值是允许访问服务的域的列表。由于*用作通配符匹配,因此值[*]允许从任何位置访问。


(强调我的。)

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

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


默认情况下,cors_enable/0不编写任何内容。

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

编辑:您编辑的代码具有与CORS无关的基本问题。请减少到最小的例子。您可以通过以下方法查看问题所在:


?- server(4050).启动服务器(例如)
在Web浏览器中访问http://localhost:4050


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

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

处理(请求):-
cors_enable,
reply_json(test {x:1,y:2})。

10-06 07:46
查看更多