javascript - 未获取返回有效 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,但它也不起作用?什么是问题?
解决方案
问题在于我没有在 JAVA Api 中包含 CORS 响应库。Thogh Postman 可以在没有它的情况下做出响应。浏览器没有。
推荐阅读
- java - 我怎么知道 Kotlin 是为现有的 java 类创建了一个等价的类,还是使用了原来的类?
- netlogo - 设置列表中所有代理的颜色 Netlogo
- javascript - Paypal Checkout (javascript) Create Order - 如何填写送货名称和电子邮件?
- swift - 使用蒙版时“WithAnimation”不起作用?
- javascript - 按键后将输入值转换为百分比 (0.00%)
- ocaml - ocaml 类型的初学者
- java - 在类路径资源 [applicationContext.xml] 中定义名称为“userService”的 bean 创建错误:
- kdb - kdb - 列存在的 KDB 应用逻辑 - 数据验证
- c# - FileNotFoundException 无法加载文件或程序集'office,版本 = 15.0.0.0
- sails.js - 帆属性中的“示例”选项是什么意思?