【问题标题】:$http results in XML parse error?$http 导致 XML 解析错误?
【发布时间】:2014-05-23 23:47:12
【问题描述】:

我正在尝试使用 angularJS 中的 $HTTP 方法来调用我的宁静 Web 服务。

当我在浏览器中使用我的 Web 服务 URL 时,我得到 APPLICATION/JSON 类型的结果。

{"id":20418,"content":"Hello, World!"}

我的网络服务网址:

http://localhost:8082/vlinkRest/rest/employee/angular

但是当我尝试从我的 HTML 文件中的 angularJS 调用我的 Web 服务时,我收到以下错误:

<?xml-stylesheet href="chrome://global/locale/intl.css" type="text/css"?>
<parsererror>
    XML Parsing Error: not well-formed Location: chrome://browser/content/browser.xul Line Number 1, Column 1:
    <sourcetext>{"id":20418,"content":"Hello, World!"} ^</sourcetext>
</parsererror>

这是我的 angularJS 代码:

function Hello($scope, $http) {
    $http.get('http://localhost:8082/vlinkRest/rest/employee/angular', {headers: {'Accept': 'application/json'}}).
        success(function(data) {
        alert('0');
        $scope.greeting = data;
    }).error(function (data, status, headers, config) {alert('1:'+data+':'+status+":"+headers+":");});

}

如果我使用以下 URL,我的代码可以正常工作:

http://rest-service.guides.spring.io/greeting

当我直接在浏览器中运行这两个 URL 时,它们在浏览器中显示相同的结果。我还检查了直接运行时都产生类型的输出:

application/json

但是对于我的网络服务,当从 angularJS 代码执行时,HTTPFox 会出现以下错误:

00:00:01.387    1.154   423 168 OPTIONS 200 application/xml http://localhost:8082/vlinkRest/rest/employee/angular

当我直接在浏览器中运行 URL 时,我得到以下信息:

00:00:40.067    0.166   319 110 GET 200 application/json    http://localhost:8082/vlinkRest/rest/employee/angular

我可能正在做一些业余的事情,但欢迎任何帮助!

谢谢

【问题讨论】:

  • 听起来尽管您要求的是 json,但它正在尝试返回 xml。从请求配置中删除 {headers: {'Accept': 'application/json'} 会发生什么?
  • 还是一样。我添加了标题选项,认为它会解决问题,但它没有。
  • 是的,实际上,我认为 $http 默认使用Accept: application/json 代替.get()。当您通过在浏览器中输入 URL 进行测试时,您是否使用过 Postman 或类似的东西?还是直接在地址栏中输入?
  • 我在 Firefox 的地址栏中输入 URL 并使用 HTTPFox for Firefox 测试结果。
  • 如果您的 server/rest 端点在不同的源上运行,chrome(和其他一些浏览器)将为 AJAX CORS 请求触发预检 OPTIONS 请求。 (检查 w3.org/Protocols/rfc2616/rfc2616-sec9.html 以获取 OPTIONS 请求)。您的服务器还必须使用标头 Access-Control-Allow-Origin: * 进行响应。 (可能类似:stackoverflow.com/questions/21455045/…)

标签: javascript json angularjs rest


【解决方案1】:

不确定 $HTTP 有什么问题。我创建了一个服务和工厂,并在我的应用程序服务器 web.xml 文件中添加了 CORSFilter 过滤器。它现在工作正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多