Solved

Angular JS $http post is not workng

Posted on 2016-08-24
4
51 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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Implement virtual paging in ag-grid 2 979
Display drop down in angular 3 88
Angular JS question 24 52
New to Angular - are these sections correct? how to do the $scope 19 58
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.
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

730 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