Angularjs $http.get method not working - javascript

HI i have a micro service running on port 8501.
#RestController
#RequestMapping("/feeds")
public class FeedsController {
#RequestMapping(method = GET)
ResponseEntity<?> findAllFeeds() {
return new ResponseEntity<String>("Hello", OK);
}
}
when i add url http://localhost:8501/feeds, browser displays "Hello". Now i am trying to access this through angularjs get call
in my AngularJs my code is
'use strict';
var app = angular.module('commentsjsApp');
app.controller('MainCtrl', function ($scope,$http) {
$http.jsonp('http://localhost:8501/feeds').success(function(data, status, headers, config){
console.debug("Data : "+data+ "Status");
}).error(function(){
console.debug("error");
});
EDIT :
In Network tab (firebug) i can see the GET with 200 status and response is "Hello". Why i am getting the error in console then? Can any one kindly help me.
and when i run this angularjs app. the following output on console as shown in image

You are requesting a JSONP data, but the server is returning a string. Return a proper JSON object from the server to fix the issue.
Note: Hello world is not valid JSON, but "Hello World" is.

You need to add the header 'Access-Control-Allow-Origin' in the response, since your calling from localhost:9000 to localhost:8501 (they are technically different servers).
#RequestMapping(method = GET)
ResponseEntity<?> findAllFeeds(HttpServletRequest httpRequest,
HttpServletResponse httpResponse) {
httpResponse.addHeader("Access-Control-Allow-Origin",
"http://127.0.0.1:9000");
return new ResponseEntity<String>("Hello", OK);
}

Sometimes Angular requires the colon in the URL to be quoted, try this:
$http.get('http://localhost\\:8501/feeds').success(function(data, status, headers, config){
console.debug("Data : "+data);
}).error(function(){
console.debug("error");
});

Related

Calling spring boot webservice from angularjs with get method, is not working is giving 500 status error

I have created a webservice to get the excel file from server location to my local machine. with the help of springboot and angularjs. Now my URL is generating well, but i am getting 500 error.
my code is given below ..
My Springboot class:
class MyWebserviceClass
{
#RequestMapping(method = RequestMethod.GET, value = "digital_data/{digital_file}", produces = "application/vnd.ms-excel")
public getExcelFileFromServer((HttpServletResponse response, #PathVariable("digital_file") String digital_file) throws IOException {
{
// my download logic will we here
}
AngularJS controller method
digitalService.getDigitalData(digital_file).then (function(res) {
var blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
saveDigitalData(blob, digital_file);
}, function(errRes) {
$scope.showErrorMessage("Error");
})
};
AngularJS Service Layer
digitalService
{
function getDigitalData(digital_file) {
var url = 'digital_data/'+file_name;
return $http.get(url,{
transformRequest: angular.identity,
headers: {'Content-Type': undefined},
responseType:"arraybuffer"
});
}
}
After running this code, web service URL generating properly but code is not able to call springboot webservice.
Generated URL: http://localhost:8080/RMS/digital_data/user_review.xlsx
Error:
{resStatus: -3, appErrorMsg: "Could not find acceptable representation"}
Exception:
com.media.MediaController.MyWebservice.getExcelFileFromServer(javax.servlet.http.HttpServletResponse,java.lang.String) throws java.io.IOException={[/digital_data/{digital_file}],methods=[GET],produces=[application/vnd.ms-excel]}}
could you guys please help me, as this is my first webservice . it might be possible i am doing some silly mistake..
And sorry for typo mistake...
I removed the file extension from the filename for URL, and added into springboot functionality.
Example: URL would be http://localhost:8080/RMS/digital_data/user_review instead of http://localhost:8080/RMS/digital_data/user_review.xlsx.. and it is working fine.

GET Service call is not getting called from Controller

i am trying to introduce Angular into one of my old application. But not sure why this is not calling the Service. Below is the Code in the JS File. Earlier i got error in browser saying $http cannot be resolved . So i just passed it in the function.
var app = angular.module('ldlApp', []);
app.controller('ldlController', function($scope,$http) {
console.log(" Inside Controller **** ");
$scope.message = 'Hello from LDL Controller !!!! ';
$scope.BLT_LDL_DECESION_LOAN_DATA = [];
console.log(" Going to Hit the Service ***** ");
$http.get("/Services/ldl/getdetails")
.then(function(response) {
$scope.BLT_LDL_DECESION_LOAN_DATA = response.data;
console.log("BLT_LDL_DECESION_LOAN_DATA:
"+JSON.stringify($scope.BLT_LDL_DECESION_LOAN_DATA));
});
});
Below is the REST Controller in java File
#RestController
public class LoanDecesionController {
#RequestMapping(value = "/Services/ldl/getdetails", method = RequestMethod.GET)
#ResponseBody
#Transactional
public List<LinkedHashMap<String, Object>> getdetails() throws Exception {
System.out.println(" Inside Service **** ");
List<LinkedHashMap<String, Object>> dataMap = new ArrayList<LinkedHashMap<String, Object>>();
LinkedHashMap<String, Object> responsedataMap = new LinkedHashMap<>();
responsedataMap.put("SUCESS", "Called the service ");
dataMap.add(responsedataMap);
return dataMap;
}
}
In Browser i could see message like
Inside Controller ****
Going to Hit the Service *****
Below is something i am seeing in network tab .
Request URL: https://*****-*****-*****.com/Services/ldl/getdetails
Request Method: GET
Status Code: 302 Found
Remote Address: 10.***.***.49:553
Referrer Policy: no-referrer-when-downgrade
But i am not getting the sysouts in controller. So whether the problem is really with response or is it hitting the service.
when using #Transactional and #ResquestMaping spring boot don't auto-configure URL mappings. remove #Transactional from your method and try to manage transactions somewhere else in your code
It looks like my existing application is blocking the URL and not allowing to hit any other URLs . Thanks everyone for the help and giving insight to the problem.

How to return string as a response to http request

In my Maven app I have mapped put http request onto this function(using spring framework), and I want to check something inside it and send response as text. Then I want to send that request from angularjs and store that response into some variable from angularjs controller. This is what I have tried.
#RequestMapping(path="/play", method={RequestMethod.POST}, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public String someFunction(){
//...
return "some text";
}
$scope.getResponse = function(param1, param2...){
$http.post("url..").then(
function(response){
$scope.response = response.data.response;
console.info('success');
},
function(response){
console.info('failure');
})
}
Http is mapped correctly and works from browser, problem is how to store textual response into some angularjs variable from controller.
It seems $http finds it difficult to parse the invalid JSON data in the response.
We have produces = {MediaType.APPLICATION_JSON_UTF8_VALUE} in there for the API and sending out plain text. That's why it goes to the failure handler.
Change the media type to MediaType.TEXT_PLAIN_VALUE and see if it works...

AngularJS $http.get service

I'm using a $http.get service in my app, which is retrieving xml data for conversion. In my plnkr I also have a file named data.xml which has the same formatted xml file as in the url I entered. When I enter data.xml into the $http.get function, the data is received and my app works. When I try plugging in the url, however, it crashes. The browser tells me that I have an illegal token on the line with the url. I've looked over the documentation on the angularjs site and I can't find why I'm getting this error. I'm new to angular and don't have much experience with this service. How can I pull the data from that url?
My current code:
factory('DataSource', ['$http', function($http) {
return {
get: function() {
return $http.get(
'http://50.22.49.237/XMLFiles/ReformatedSample.xml', {
transformResponse: function(data) {
var x2js = new X2JS();
var json = x2js.xml_str2json(data);
return json;
}
}
)
success(function(data, status) {
callback(data);
})
}
}
}]);
Any help is appreciated.
Have you checked the console? Maybe you have a CORS issue.

AngularJS HTTP Call / Response

This is probably something very simple but I am having some problem making an HTTP GET request, getting the data back, and attaching it onto the javascript global window variable.
Simple HTTP Call:
$http.get("production/dashboard?dashboard_type=A").success((data) ->
$scope.pods = data;
window.pods = $scope.pods.to_json;
window.type = 'A';
alert(window.pods)
alert(window.type)
alert "success1"
return
).error (data, status, headers, config) ->
return
Upon execution, I am getting:
1. Alert("undefined")
2. Alert("A")
I thought that the promise of the http request will get resolved when the response returns?
I checked the Network tab and there is indeed JSON data being sent back as the response to the request.
I must be missing something simple...
$http.get("production/dashboard?dashboard_type=A")
.success(function(data) {
$scope.pods = data;
window.pods = $scope.pods;
window.type = 'A';
alert(window.pods);
alert(window.type);
alert("success1");
return
}).error (function(data, status, headers, config){
return;
});
This is assuming it has access to the window where your code is. Is this wrapped in a module and controller?
As we need json data to get from $http.. Trying putting .json like below.
$http.get('/products.json')
Regarding your another issue.. you might get a hint with this link AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

Categories