对运行 SparkJava 的本地主机服务器的请求使用邮递员工作,但不能使用浏览器中的 javascript

Posted

技术标签:

【中文标题】对运行 SparkJava 的本地主机服务器的请求使用邮递员工作,但不能使用浏览器中的 javascript【英文标题】:Requests to a localhost server running SparkJava work using postman, but not with javascript in a browser 【发布时间】:2018-01-24 04:24:03 【问题描述】:

我使用 SparkJava API 从 Eclipse 运行这个简单的服务器:

public static void main(String[] args) 

    BasicConfigurator.configure();
    staticFileLocation("/public");
    port(5678);
    enableCORS("*", "*", "*");

    get("/hello", (request, response) -> "Hello World!");

    post("/hello", (request, response) ->
        "Hello World: " + request.body()
    );




private static void enableCORS(final String origin, final String methods, final String headers) 

    options("/*", (request, response) -> 

        String accessControlRequestHeaders = request.headers("Access-Control-Request-Headers");
        if (accessControlRequestHeaders != null) 
            response.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
        

        String accessControlRequestMethod = request.headers("Access-Control-Request-Method");
        if (accessControlRequestMethod != null) 
            response.header("Access-Control-Allow-Methods", accessControlRequestMethod);
        

        return "OK";
    );

    before((request, response) -> 
        response.header("Access-Control-Allow-Origin", origin);
        response.header("Access-Control-Request-Method", methods);
        response.header("Access-Control-Allow-Headers", headers);
        // Note: this may or may not be necessary in your particular application
        response.type("application/json");
    );

我在网页上运行了这个 javascript

var oReq = new XMLHttpRequest();
oReq.open("POST", "localhost:5678/hello", true);
var test = oReq.send("TESTING");
document.getElementById("TEST").innerhtml = test;

当我通过 Postman chrome 应用程序发送请求时,我可以发送请求并获得响应,但是当我在 chrome 中运行此脚本时,我收到以下错误:

XMLHttpRequest 无法加载 localhost:5678/hello。跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https。

我也尝试在 Firefox 和 Edge 中运行该脚本,但仍然出现网络错误。为什么请求可以在 Postman 中工作,但在从任何浏览器运行脚本时却不行?

【问题讨论】:

它通过 Postman 工作,因为您直接调用服务器。这里不涉及 CORS。但是,当您通过 javascript 执行此操作时,CORS 就会发挥作用。我看到你已经添加了相应的标题。那应该可以解决问题。但是 req url 不包含 http 方案。您需要将localhost:5678/hello 更改为http://localhost:5678/hello @yaswanth 谢谢!解决了它,我不敢相信我错过了这么简单的东西。 让我添加它作为答案。 【参考方案1】:

它通过 Postman 工作,因为您直接调用服务器。这里不涉及 CORS。但是,当您通过 javascript 执行此操作时,CORS 就会发挥作用。我看到你已经添加了相应的标题。那应该可以解决问题。但是 req url 不包含 http 方案。你需要把localhost:5678/hello改成http://localhost:5678/hello

【讨论】:

以上是关于对运行 SparkJava 的本地主机服务器的请求使用邮递员工作,但不能使用浏览器中的 javascript的主要内容,如果未能解决你的问题,请参考以下文章

docker容器连接到我的本地主机,因此它可以向在我本地运行的应用程序发送http请求[重复]

DNS之主从服务器的构建和dig命令的使用

PHP 图片上传适用于本地主机,但不适用于 GoDaddy 服务器

错误请求 - 从跨 LAN 访问本地主机 Web API 或 Web 应用程序时主机名无效

如何让红隼网络服务器监听非本地主机请求?

将带有第一个请求的 html 页面返回到在端口 5000 本地运行的 Json Rpc Dispatcher 服务器