不提取返回有效JSON的Localhost API

时间:2018-06-12 06:51:05

标签: javascript json tomcat cors

我正在使用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,它也无法正常工作?什么问题?

1 个答案:

答案 0 :(得分:0)

这个问题是我没有在JAVA Api中包含CORS响应库。 Thogh Postman可以不给予回应。浏览器没有。