【发布时间】:2014-03-09 02:42:50
【问题描述】:
我无法使用 angularjs $http 从 rest webservice 读取 JSON。我在一个返回 JSON 的不同项目中有一个简单的休息 web 服务。当我尝试从角度访问休息服务时,它会进入错误部分。
以下是我的代码: Java 中的 Restful 服务:
package com.demoapp.rest;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
/**
* REST Web Service
*/
@Path("Employee")
public class EmployeeResource {
@Context
private UriInfo context;
/**
* Creates a new instance of EmployeeResource
*/
public EmployeeResource() {
}
/**
* Retrieves representation of an instance of com.demoapp.rest.EmployeeResource
* @return an instance of java.lang.String
*/
@GET
@Produces("application/json")
public String getJson() {
//TODO return proper representation object
return "({\"id\":3,\"name\":\"Joe\"})";
}
/**
* PUT method for updating or creating an instance of EmployeeResource
* @param content representation for the resource
* @return an HTTP response with content of the updated or created resource.
*/
@PUT
@Consumes("application/json")
public void putJson(String content) {
}
}
Angularjs 代码:
angular.module('myApp.controllers', [])
.controller('MyCtrl1', ['$scope', '$http', function($scope, $http) {
$http.jsonp(
/*Doesn't work*/ 'http://localhost:8080/mavenproject1/webresources/Employee?callback=JSON_CALLBACK'
/*Works*/ /*'http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&callback=JSON_CALLBACK'*/
)
.success(function(data) {
console.log('Success '+data);
})
.error(function(data) {
console.log('Error '+data);
});
}])
.controller('MyCtrl2', [function() {
}]);
我的第一个 url (localhost..) 出现错误,并且相同的 angularjs 代码适用于另一个公共的 restful 服务。
谁能告诉我为什么 angularjs 在控制台中为 (http://localhost..) RESTful 服务返回错误并为 (http://api.openweathermap.org/....) 成功?
我到底哪里错了?
【问题讨论】:
-
先在浏览器中试试你的 localhost url,它工作正常吗?
-
是的,localhost url 在浏览器中有效。 url - localhost:8080/mavenproject1/webresources/Employee 并返回 - ({"id":3,"name":"Joe"})
标签: json web-services angularjs rest