Solved

Angular JS $http post is not workng

Posted on 2016-08-24
4
44 Views
Last Modified: 2016-09-17
I am trying post data to Rest web api using Angular JS $http.post.
I am getting the following error when debug the page. Any suggestions please.

XMLHttpRequest cannot load path/to/api. Response to preflight request doesn't pass access control check: No 'Access-
Control-Allow-Origin' header is present on the requestd resource.Origin 'http://localhost:12345' is therefore not allowed access.The respons had HTTP status code 500 please see the below Html and controller code.

<body ng-app="MyApp">
<table class="Tbl1" ng-controller="MyCtrl">
<tr width="100%">
<td align="right">
<label class="genLabel" for="usr">UserName:</label>
</td>
<td align="right">
<input type="text" class="genTextBox" id="usr" ng-model="userName">
</td>
</tr>
<tr>
<td align="right">
<label class="genLabel" for="comment">Comments:</label>
</td>
<td align="right">
<textarea rows="8" id="comment" class="genTextBox" ng-model="feedbackComments"></textarea>
</td>
</tr>
<tr>
<td align="right">
</td>
<td>
<button type="button" class="greenButton" ng-click="submitFeedback(UserName,feedbackComments)">Submit</button>

</td>
</tr>
<tr>
<td align="right">
</td>
<td>
<label class="genLabel" for="comment">{{statusMessage}}</label>

</td>
</tr>
</table>
</body>

Open in new window


var MyApp = angular.module('MyApp',[]);
MyApp.Controller('MyCrtl,function($scope,$http)
{

$scope.submittedFeedBack =
{
   UserName: "",
   feedbackComments: ""
}
$scope.submifeedback = function(UserName,feedbackComments)
{
  $scope.submittedFeedBack.UserName = UserName;
  $scope.submittedFeedBack.feedbackComments = feedbackComments;
 var apiurl = 'path/to/api';
 var jsonSubmittedFeedback = angular.toJson($scope,submittedFeedBack);
 $http({
url: apiurl,
dataType: 'json',
method: 'POST',
data: jsonSubmittedFeedback,
headers: {
   "Content-Type": "application/json",
   "Authorization": "UserName xx"

}
}).success(function(response){
$scope.statusMessage = "Feedback successfully submitted";

}).error(function(error){
$scope.statusMessage = "Feedback not submitted";

});


}


});




});

Open in new window


Thanks
0
Comment
Question by:KavyaVS
  • 2
  • 2
4 Comments
 
LVL 2

Accepted Solution

by:
Kyaw Wanna earned 500 total points
ID: 41769690
Hello,

According to your error detail, it would be the problem about CORS (Cross Origin Resource Sharing) which is sharing and requesting the resource across the different origins.
It might not be possible to fix by angular itself.
Here are a few ways to solve this issue.

Option 1
Configure CORS header on your Server side programming. Suppose that your server side page is developed by asp.net.

For ASP.NET Page
You can add the header through ASP.NET by adding the following line to your source pages:
Response.AppendHeader("Access-Control-Allow-Origin", "*");

Open in new window


For ASP.NET Web API
Add the Microsoft.AspNet.WebApi.Cors NuGet package to your project
public static void Register(HttpConfiguration config)
{
     config.EnableCors();
}

[EnableCors(origins: "http://yourdomain.com", headers: "*", methods: "*")]
public class TestController : ApiController
{
    // your methods
}

Open in new window


Option 2

Using JSONP in your client script

Example :

$.ajax({
            crossDomain: true,
            type:"GET",
            contentType: "application/json; charset=utf-8",
            async:false,
            url: "http://your url address/?callback=?",
            data: {key:value},
            dataType: "jsonp",                
            jsonpCallback: 'successcallback'
        });

Open in new window


Option 3

Using XMLHttpRequest
You can also refer the following URL for other option :
Creating the XMLHttpRequest Proxy
0
 

Author Comment

by:KavyaVS
ID: 41771146
Thanks for your response. The Rest Web API developed using java. Any suggestions for Rest Web API in java.

Thanks
0
 
LVL 2

Assisted Solution

by:Kyaw Wanna
Kyaw Wanna earned 500 total points
ID: 41771170
Hello,

Basically, it should need to configure your server side to accept CORS calls by defining which origins and which HTTP methods are allowed.

Please check the following articles about using "Jersey" for CORS.

Articles
http://www.codingpedia.org/ama/how-to-add-cors-support-on-the-server-side-in-java-with-jersey/
http://crunchify.com/what-is-cross-origin-resource-sharing-cors-how-to-add-it-to-your-java-jersey-web-server/

Website
https://jersey.java.net/
0
 

Author Closing Comment

by:KavyaVS
ID: 41803015
Thanks
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

832 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question