angular js $http rest controller status code 0 - Java @ Desk

Friday, February 17, 2017

angular js $http rest controller status code 0

angular js $http rest controller status code 0

Angular JS $hhtp returns the status code 0 on calling the get request from the spring rest controller. The rest controller in the example below produces "application/json".

The response come fine if the URL is tested in the browser. It successfully prints the response on the chrome browser, but the same request returns the status code 0 if called from angular js $http. Below is the sample request and spring rest controller for the same.

angularController.js
var app = angular.module('customerApp', []);
app.controller("customerController", function($scope, $http) {
 $http.get('http://localhost:8060/customers').then(
   function successCallback(response) {
          $scope.customer = {name: response.data.name, id: response.data.id};
   }, function errorCallback(response) {
   });
});


CustomerController.java
package com.accenture.restviability.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.acc.auto.service.request.Customer;

@RestController()
public class CustomerController {

 @RequestMapping(method = RequestMethod.GET, path = "/customers", produces = MediaType.APPLICATION_JSON_VALUE)
 public ResponseEntity<Customer> getCustomers() {
  System.out.println("Entered in Get Customers");
  List<Customer> customers = new ArrayList<Customer>();
  Customer customer = new Customer();
  customer.setName("Kumar");
  customer.setId("1");
  return new ResponseEntity<Customer>(customer, HttpStatus.OK);
 }
}


The above angular method returns the status code 0 on calling the spring rest controller. The issue occure because of HTTP Access Control CORS issues.

Angular does not consume the response from the server that does not include Access-Control-Allow-Origin header in the response. The server responding back the angular JS calls must include the headers specified by CORS. In order to make it work, you need to include the below annotation of Spring.

@CrossOrigin(maxAge = 3600) from import org.springframework.web.bind.annotation.CrossOrigin;
package of Spring







No comments:

Post a Comment