3

我正在尝试通过 UI 应用程序在我的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?

我已经检查了swi-prolog 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();
4

0 回答 0