我的项目在 www.example.com:8888 上运行,并且我的项目需要 API ,该API在不同端口上的同一服务器上运行(< strong> www.example.com:8081 )。现在,在与 API
进行通信时,我遇到一个 CORS 问题。下面是我的API的JAVA代码摘录:
@GET
@Path("/getFiles")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response gettingJsonFiles(@QueryParam("data") String data) throws IOException {
List<org.json.JSONObject> jsonList=JsonService.gettingJsonFiles(data);
return Response.ok(jsonList.toString()).header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.header("Access-Control-Allow-Headers", "X-Requested-With")
.allow("OPTIONS").build();
}
答案 0 :(得分:0)
添加第@CrossOrigin(origins = "http://localhost:9000")
行以允许Cors
您也可以创建自定义过滤器-查看-https://howtodoinjava.com/servlets/java-cors-filter-example/
答案 1 :(得分:0)
请回复CORS请求,以确认是否存在您提到的标题。
请尝试将以下标头与现有标头一起添加:
@Override
public Map<String, String> getParams() throws AuthFailureError {
Map<String, Object> params = new HashMap<>();
params.put("clientid", clientidd);
params.put("doc_type",myList);
params.put("taxpreparerid", taxpreid);
System.out.println("my lIst"+myList);
System.out.println(params);
return null;
}
结果代码应为:
"Access-Control-Allow-Credentials", "true"
此外,如果您要随请求发送任何自定义标头,则应将其添加到@GET
@Path("/getFiles")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response gettingJsonFiles(@QueryParam("data") String data) throws IOException
{
List<org.json.JSONObject> jsonList=JsonService.gettingJsonFiles(data);
return Response.ok(jsonList.toString())
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
.header("Access-Control-Allow-Headers", "X-Requested-With")
.header("Access-Control-Allow-Credentials", "true")
.build();
}
中。