2016-10-16 27 views
2

我在序言中遇到cors问题。我认为它不起作用。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帖子序言服务器时,它说

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. 

阿贾克斯,我用它来发布。

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); 
    } 
    }) 

我该如何解决这个问题?

-Edited 现在我修复了一些我的代码,但它仍然无法工作。

回答

4

library(http/http_cors)documentation报价:

由于CORS是一个安全的RISC(请参阅参考资料),它被默认禁用。 它通过设置http:cors启用。此设置的值是允许访问服务的域列表。由于*用作通配符匹配,因此值[*]允许从任何地方访问。

(重点煤矿)

因此,在你的服务器,你可能必须包括设置:

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

默认情况下,没有cors_enable/0写的。

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

编辑:您编辑的代码具有有无关与  CORS基本问题。请将此减至最小示例。你可以看到什么是错的:

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

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

这里是handle/2一个小骷髅,你可以根据需要扩展:

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

我说行添加到我的代码。但它仍然无法正常工作。 – ReiiYuki

+0

现在我编辑这个帖子来显示我的代码。 – ReiiYuki

+0

我已经更新了我的答案。请注意,几个无关的问题会遮盖您的实际问题。下次请尽可能缩短范例。 – mat