我无法使用angularjs $ http从其他webservice中读取JSON。我在一个返回JSON的不同项目中有一个简单的休息webservice。当我试图从角度打休息服务时,它会转到错误部分。
下面是我的代码: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(本地主机。)和同样angularjs代码适用于另一个公共的安宁服务。
任何人都可以请告诉为什么angularjs为(http://localhost.。)宁静的服务在控制台中返回错误并且成功为(http://api.openweathermap.org/...。)?
我到底错在哪里?
首先尝试在您的浏览器中的localhost url,它工作正常吗? –
是的,本地主机url在浏览器中工作。 url - http:// localhost:8080/mavenproject1/webresources/Employee并返回 - ({“id”:3,“name”:“Joe”}) –