首页 > 解决方案 > 未获取返回有效 JSON 的 Localhost API

问题描述

我正在使用 Apache Tomcat 来托管我的本地服务器,并且我已经使用 jersey 创建了 Java REST API。现在我返回 JSON 对象,当我在浏览器或邮递员中打开它时它工作正常,它也是有效的 JSON 对象。

[
{
    "algo_name": "First Come First Served",
    "running_time": 13.125098
},
{
    "algo_name": "Shortest Job First",
    "running_time": 22.620548
},
{
    "algo_name": "Shortest Remaining Time",
    "running_time": 21.530843
},
{
    "algo_name": "Non-Preemptive Highest Priority First",
    "running_time": 15.412454
},
{
    "algo_name": "Round Robin",
    "running_time": 20.904071
}
]

但是当我尝试使用 url“ http://localhost:8080/algo/webapi/handler/100/100/100/4 ”从 html 文件中的 javascipt 读取它时,我无法从中获取 json。

let url = 'http://localhost:8080/algo/webapi/handler/100/100/100/4';

fetch( url, {
    method: 'get'
}).then( function( response ) {
    alert("Success");
}).catch( function( err ) {
    alert("OOps");
});

上面的代码在我的浏览器中给出了“OOps”。我无法从本地机器上的 javascript 获得响应。以下是浏览器中的错误日志。

Failed to load http://localhost:8080/algo/webapi/handler/100/100/100/4:
No 'Access-Control-Allow-Origin' header is present on the requested
resource.Origin 'null' is therefore not allowed access. If an opaque 
response serves your needs, set the request's mode to 'no-cors' to fetch the 
resource with CORS disabled.

我也尝试过返回 xml,但它也不起作用?什么是问题?

标签: javascriptjsontomcatcors

解决方案


问题在于我没有在 JAVA Api 中包含 CORS 响应库。Thogh Postman 可以在没有它的情况下做出响应。浏览器没有。


推荐阅读