java – 使用com.sun.net.httpserver的CORS

我正在使用此代码,但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();

我究竟做错了什么?

最佳答案 我有同样的问题,但我用以下代码解决了我的问题:

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

这适合我.

点赞