【问题标题】:CORS Allow all on same Server different Ports in JAVACORS 允许所有在同一服务器上的不同端口在 JAVA 中
【发布时间】:2019-03-17 07:07:28
【问题描述】:

我的项目在 www.example.com:8888 上运行,我的项目需要一个 API,它在不同端口的同一服务器上运行(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();

}

【问题讨论】:

    标签: amazon-web-services api server cors port


    【解决方案1】:

    添加行 @CrossOrigin(origins = "http://localhost:9000") 以允许 Cors

    您也可以创建自定义过滤器 - 查看 -https://howtodoinjava.com/servlets/java-cors-filter-example/

    【讨论】:

    • 感谢您的回复@anshuVersatile 我目前没有使用任何框架,我无法继续!有图书馆吗?
    【解决方案2】:

    请在响应 CORS 请求时检查您提到的标头是否存在。

    请尝试将以下标题与现有标题一起添加:

    "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();
    }
    

    此外,如果您通过请求发送任何自定义标头,则应将其添加到 "Access-Control-Allow-Headers"

    【讨论】:

    • 感谢您的回复@Sangam Belose 但我仍然无法继续,当我添加此标头时,API 甚至不公开可用。现在直接通过浏览器和更早的请求时显示 404 错误它是可用的。
    • 404 不应该只添加这些更改..我希望你已经重新启动了应用服务器。
    猜你喜欢
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 2011-04-21
    • 2022-01-02
    • 1970-01-01
    • 2019-01-21
    相关资源
    最近更新 更多