Solved

Angular JS $http post is not workng

Posted on 2016-08-24
4
38 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Thanks
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

You have this traditional web application that refreshes the whole page each time you navigate and you think it's a good time to convert it to a Single-Page approach. What should you know in advance? Read on, I'll guide you through it.
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

763 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now