Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Angular JS $http post is not workng

Posted on 2016-08-24
4
Medium Priority
?
79 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
[X]
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
  • 2
  • 2
4 Comments
 
LVL 2

Accepted Solution

by:
Kyaw Wanna earned 2000 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 2000 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

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

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…
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.
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
Suggested Courses

618 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