我正在尝试实现基于 java 的 web 服务服务器,它返回 Json 和基于 java 脚本的 web 服务客户端。这是我的java部分:
@Path("/myapp")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class MyRecommender {
@POST
@Path("/recs")
public Response getRecommendations() {
//Assume recommendation List contains some Recommendation objects
//I removed it for simplicity.
List<Recommendation> recommendation;
JsonArrayBuilder builder = Json.createArrayBuilder();
for (Recommendation rec : recommendations) {
builder.add(Json.createObjectBuilder().add("firstPersonName", "\"" + rec.getFirstPerson().getName() + "\"")
.add("firsPersonURL", "\"" + rec.getFirstPerson().getURL() + "\"")
.add("secondPersonName", "\"" + rec.getSecondPerson().getName() + "\"")
.add("secondPersonURL", "\"" + rec.getSecondPerson().getURL() + "\"")
.add("score", "\"" + rec.getSimilarity() + "\""));
}
JsonArray jsonData = builder.build();
return Response.ok(jsonData, MediaType.APPLICATION_JSON).header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST").allow("OPTIONS").build();
}
}
}
现在,当我从 js 客户端调用这个函数时,我得到:
POST http://localhost:8080/myapp/recs 500 (Request failed.)
但是,当我替换 for 循环并返回以下代码片段时,我在 js 中得到了正确的响应。
更改部分:
// remove for loop and change jsonData type.
String jsonData = "{\"name\":\"John\"}";
return Response.ok(jsonData, MediaType.APPLICATION_JSON).header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST").allow("OPTIONS").build();
所以,我想知道可能是什么问题?自从我第一次使用网络服务以来,我在调试代码时遇到了一些困难。
EDIT
顺便说一句,当我尝试第一个版本的 getRecommendations() 函数(带循环)时,我还收到另一个错误
XMLHttpRequest cannot load http://localhost:8080/myapp/recs.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3000' is therefore not allowed access.
The response had HTTP status code 500.
但正如我所说,当我删除循环并将第二个代码片段放入 getRecommendations() 函数时,两个错误都消失了,我在网站中得到了响应。
EDIT2
当我用下面的代码更改 getRecommendations() 函数的循环和返回语句时,我再次get同样的错误
JsonObject value = Json.createObjectBuilder()
.add("name", "John").build();
return Response.ok(value, MediaType.APPLICATION_JSON).header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST").allow("OPTIONS").build();
EDIT 3
据我了解,createObjectBuilder().build()
or JsonArrayBuilder.build()
返回一个JSON object
我的 getRecommendations() 函数中的以下构建语句甚至没有运行。所以,我想我的问题如何向该对象授予 Access-Control-Allow-Origin 权限?