【问题标题】:Can't get a response at CORS request无法在 CORS 请求中得到响应
【发布时间】:2016-01-24 22:25:41
【问题描述】:

我有以下 Javascript 代码 向服务器发出 XMLHttpRequest:

function createCORSRequest(method, url) {

  var xhr = new XMLHttpRequest();
  xhr.open(method, url, true);
  return xhr;
}


function makeCorsRequest(word) {

    var url = "https://localhost:8080/Method/Dictionary/" + word;

    var xhr = createCORSRequest('GET', url);
    xhr.onload = function() {
        var responseText = xhr.responseText;
        document.querySelector("#bar").innerHTML = responseText;
    };

    xhr.onerror = function() {
        document.querySelector("#bar").innerHTML = 'Connection not allowed';
    };

    xhr.send();
}

makeCorsRequest("word");

在服务器上,我有一个 REST 结构(使用 Jersey 编写),类似于:

@Path("/Dictionary")
public class Main{

public Definition returnDefinition(String word){

    Definition definition = new Definition();
    try{

    ...//play with Definition object
    return definition;
    }


    catch(IOException IOE){
        ...
        return definition;
    }

}


@Path("{word}") 
@GET 
@Produces("text/xml ; charset=UTF-8")                   //"Definition" is already set as a XMLRoot element
public Definition main (@PathParam("word") String word){
    return returnDefinition(word);
}

}

我尝试在两种环境中提出这个请求:

第一个环境:JS代码在普通网页中。在这种情况下,我在尝试发出请求后收到以下错误:

XMLHttpRequest cannot load http://localhost:8080/Method/Dictionary/word. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

第二个环境:JS 代码在内容脚本中(它本身在 chrome 扩展中)。在这种情况下,在尝试发出请求大约 30 秒后,我收到了这个:

Failed to load resource: net::ERR_TIMED_OUT

如何进行?

编辑:我在服务器方法的开头添加了一个命令来在控制台打印一些东西。而且它没有打印出来。因此,请求没有到达服务器。

【问题讨论】:

  • 问:您的浏览器是否支持 CORS(即它是否比 IE8NEWER)?如果是这样,这听起来像是服务器配置。请参考本帖:stackoverflow.com/questions/20035101/…
  • 感谢所有努力提供帮助的人! @paulsm4 是的,这是 Chrome 的新版本!
  • @wOxxOm 当我说“在普通页面内”时,我想说它在普通的 HTML 文件中,我用浏览器打开...在第二种情况下,同样的代码在内容脚本中:)
  • 您的扩展代码绝对没有问题 - 绕过了 CORS 并发送了请求。但是,您的服务器出了点问题。顺便检查一下防火墙设置。
  • @Xan 禁用防火墙未显示任何结果。会是什么呢?我在 Glassfish 服务器上所做的并没有比我在这里展示的多...

标签: web-services rest google-chrome-extension jersey cors


【解决方案1】:

Origin 'null' 如果您在浏览器中使用file:// 协议将页面作为文件运行,而不是在本地网络服务器中设置并使用http:// 访问它,则会发生。

【讨论】:

  • 是的,在file:// 页面上进行测试总是一个坏主意,除非这是预期目标(几乎从来不是这样)。
  • 好吧,没错(虽然我真的很想猜测它为什么不管用),但是第二种情况呢?
  • 不知道那个对不起:(
  • null origin 对于 Chrome 扩展代码是正常的。但是,Chrome 扩展可以覆盖 CORS(这可以通过请求 sent 来证明)。问题出在服务器端。
  • @vtortola 没问题 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-29
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 2013-09-07
  • 2018-06-17
相关资源
最近更新 更多