请求到本地主机服务器使用邮递员运行SparkJava工作,但不是在浏览器中
问题描述:
我有这个简单的服务器从日食使用SparkJava API运行的JavaScript:请求到本地主机服务器使用邮递员运行SparkJava工作,但不是在浏览器中
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;
我可以发送请求并得到回应时,我送他们通过邮差镀铬的应用程序,但是当我在Chrome运行此脚本,我得到以下错误:
XMLHttpRequest无法加载localhost:5678/hello。协议方案仅支持跨源请求:http,data,chrome,chrome-extension,https。
我试着在Firefox和Edge中运行脚本,但我仍然收到网络错误。为什么这些请求会在Postman中运行,而不是在从任何浏览器运行脚本时运行?
答
它通过邮递员工作,因为你直接调用服务器。这里没有涉及CORS。但是,当你通过javascript CORS进入时发挥作用。我看到你已经添加了各自的头文件。这应该可以解决问题。但是,req url不包含http方案。您需要更改localhost:5678/hello
至http://localhost:5678/hello
它通过邮递员工作,因为您直接调用服务器。这里没有涉及CORS。但是,当你通过javascript CORS进入时发挥作用。我看到你已经添加了各自的头文件。这应该可以解决问题。但是,req url不包含http方案。您需要将'localhost:5678/hello'更改为'http:// localhost:5678/hello'。 – yaswanth
@yaswanth谢谢!这解决了它,我不能相信我错过了那么简单的事情。 –
让我来添加它作为答案。 – yaswanth