【问题标题】:CORS with com.sun.net.httpserver带有 com.sun.net.httpserver 的 CORS
【发布时间】:2016-05-20 16:27:06
【问题描述】:

我正在使用此代码,但 Chrome 不会显示标题,似乎没有添加:

Headers headers = httpExchange.getResponseHeaders();
headers.add("Access-Control-Allow-Headers","x-prototype-version,x-requested-with");
headers.add("Access-Control-Allow-Methods","GET,POST");
headers.add("Access-Control-Allow-Origin","*");

httpExchange.sendResponseHeaders(responseCode, responseBody.length());
OutputStream os = httpExchange.getResponseBody();
os.write(responseBody.getBytes());
os.close();

我做错了什么?

【问题讨论】:

    标签: java cors httpserver


    【解决方案1】:

    我遇到了同样的问题,但我用以下代码解决了我的问题:

    httpExchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
    
        if (httpExchange.getRequestMethod().equalsIgnoreCase("OPTIONS")) {
                httpExchange.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, OPTIONS");
                httpExchange.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type,Authorization");
                httpExchange.sendResponseHeaders(204, -1);
                return;
            }
    
    // Write here the code to GET requests
    

    这对我有用。

    【讨论】:

      猜你喜欢
      • 2020-09-24
      • 2013-10-07
      • 2013-01-21
      • 2021-05-06
      • 2014-02-28
      • 1970-01-01
      • 1970-01-01
      • 2020-11-12
      • 2014-10-14
      相关资源
      最近更新 更多