В запрошенном ресурсе отсутствует заголовок «Access-Control-Allow-Origin». Как правильно обслуживать запросы CORS в SWI-Prolog / ClioPatria? - PullRequest
2 голосов
/ 11 апреля 2019

Я пытаюсь POST некоторые данные на моем SWI-Prolog / ClioPatria сервере приложений через приложение пользовательского интерфейса, и я получаю сообщение об ошибке:

Access to XMLHttpRequest at 'http://localhost:3020/testPost' from origin 
'http://localhost:8000' has been blocked by CORS policy: No 'Access- 
Control- Allow-Origin' header is present on the requested resource 

Как правильно включить CORS на сервере?

Я проверил документацию по SWS-прологу CORS , а также это действительно хорошее руководство , но я все еще не могу заставить его работать.

Это код пролога Я работаю на сервере :

:- use_module(library(semweb/rdf11)).

:- use_module(library(http/http_client)).
:- use_module(library(http/html_write)).
:- use_module(library(http/http_json)).
:- use_module(library(http/json)).
:- use_module(library(http/json_convert)).
:- use_module(library(http/http_header)).
:- use_module(library(http/http_cors)).

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

:- http_handler(root(testPost), testPost, []).

testPost(Request) :-
  option(method(post), Request), !,
  cors_enable(Request,
              [ methods([get,post,delete],
                headers(['Access-Control-Allow-Origin'('*')]))
              ]),
  http_read_data(Request, In, [application/x-www-form-urlencoded]),
  reply_json(In.label).

Я отправляю следующий запрос с vanilla javascript :

function sendTestRequest() {

    let url="http://localhost:3020/testPost"

    var body = {
        "label": "car_label",
        "title": "car_title",
        "description": "car_description",
        "weights": [0.7, 0.3]
    }

    var formBody = new FormData();

    for (var key in body) {
        formBody.set(key, formBody[key]);
        console.log(key + " -> " + body[key]);
    }

    //create CORS request
    var xhr = createCORSRequest('POST', url);

      if (!xhr) {
        alert('CORS not supported');
        return;
      }

    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    // Response handlers.
    xhr.onload = function() {     
      var text = xhr.responseText;
          console.log("request successfully sent")
      console.log('Response from CORS request to ' + url + ': ' + text);
    };

    xhr.onerror = function() {
      console.log(xhr.responseText)
    };

    xhr.send(formBody);
}

function createCORSRequest(method, url) {

  var xhr = new XMLHttpRequest();

  if ("withCredentials" in xhr) {

    // Check if the XMLHttpRequest object has a "withCredentials" property.
    // "withCredentials" only exists on XMLHTTPRequest2 objects.
    xhr.open(method, url, true);

  } else if (typeof XDomainRequest != "undefined") {

    // Otherwise, check if XDomainRequest.
    // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
    xhr = new XDomainRequest();
    xhr.open(method, url);

  } else {

    // Otherwise, CORS is not supported by the browser.
    xhr = null;

  }
  return xhr;
}


sendTestRequest();
...