Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Angular JS $http post is not workng

Posted on 2016-08-24
4
46 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: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

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

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.
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

840 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