【发布时间】:2018-11-21 11:33:38
【问题描述】:
我正在使用 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,但它也不起作用?什么问题?
【问题讨论】:
-
你应该看看
err。 -
您是否尝试使用
cURL或 Postman 或任何其他媒介获取 JSON? -
是的,我用过邮递员。
标签: javascript json tomcat cors