2

I am literally scouring the internet looking for ways to find the right approach to post my data to server using AngularJS.

When I do a $http POST request with Angular JS it post's my data to server but fails with error message "Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin", it doesn't matter if I try it with "file:///", the result is still the same.

I tried all remedies mentioned on internet including

 app.config(['$httpProvider', function ($httpProvider) {
            $httpProvider.defaults.useXDomain = true;
            delete $httpProvider.defaults.headers.common['X-Requested-With'];
        }]);

and followed most of the instructions in this article but they do not work for me.

I also set Access-Control-Allow-Origin: * and access-control-allow-headers: Origin, X-Requested-With, Content-Type, Accept, access_token, Origin, X-Requested-With, Content-Type, Accept, access_token on server side methods but I am still getting that same error, the following is my code

var URL = "https://myURL";
        var app = angular.module('myApp', []);
        app.config(['$httpProvider', function ($httpProvider) {
            $httpProvider.defaults.useXDomain = true;
            delete $httpProvider.defaults.headers.common['X-Requested-With'];
        }]);
        app.controller('UserController', function($scope, $http){
            $scope.user = {};
            $scope.createUser = function () {
                $http({
                    url: URL,
                    data: $scope.user,
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        "access_token": "sometoken"
                    }
                }).success(function(response){
                            $scope.response = response;
                            alert('ok');
                        }).error(function(error){
                            $scope.error = error;
                            alert('error');
                        });
            }
        });

I have no idea what I am doing wrong here, please help me out.

EDIT:

The following is my preflight headers

Request URL:https://myURL
Request Method:OPTIONS
Status Code:200 OK
Request Headersview source
:host:someapp.appspot.com
:method:OPTIONS
:path:somepath
:scheme:https
:version:HTTP/1.1
accept:*/*
accept-encoding:gzip,deflate,sdch
accept-language:en-US,en;q=0.8
access-control-request-headers:accept, origin, access_token, content-type
access-control-request-method:POST
dnt:1
origin:http://localhost:8000
referer:http://localhost:8000/samplepost.html
user-agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36
Response Headersview source
access-control-allow-headers:Origin, X-Requested-With, Content-Type, Accept, access_token
access-control-allow-origin:*
alternate-protocol:443:quic
content-length:0
content-type:text/html
date:Mon, 16 Sep 2013 17:58:03 GMT
server:Google Frontend
status:200 OK
version:HTTP/1.1

And the following is my POST headers:

Request URL:someURL
Request Headersview source
Accept:application/json, text/plain, */*
access_token:dsfdsfds
Content-Type:application/json
Origin:http://localhost:8000
Referer:http://localhost:8000/samplepost.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36
Request Payloadview source
{name:adasds, email:[email protected], phone:325325325, comments:fddsfsdfsd}
comments: "fddsfsdfsd"
email: "[email protected]"
name: "adasds"
phone: "325325325"

Firefox request headers and response headers:

Response Headersview
Access-Control-Allow-Orig...    *, *
Alternate-Protocol  443:quic
Cache-Control   private
Content-Encoding    gzip
Content-Length  136
Content-Type    application/json
Date    Mon, 16 Sep 2013 18:30:17 GMT
Server  Google Frontend
Vary    Accept-Encoding
X-Firefox-Spdy  3
access-control-allow-head...    Origin, X-Requested-With, Content-Type, Accept, access_token, Origin, X-Requested-With, Content-Type, Accept, access_token
Request Headersview source
Accept  application/json, text/plain, */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Cache-Control   no-cache
Connection  keep-alive
Content-Length  100
Content-Type    application/json; charset=UTF-8
Host    someapp.appspot.com
Origin  null
Pragma  no-cache
User-Agent  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0
access_token    dsfdsfds
6
  • What is the server returning? Can you verify that the preflight is working and the server is returning the correct headers on the OPTIONS' response and the POST's response? Commented Sep 16, 2013 at 18:07
  • 1
    @TheSharpieOne added OPTIONS and POST'S response headers, the response id empty Commented Sep 16, 2013 at 18:14
  • The POST's response headers will be the most useful. Switch to Firefox with Firebug to see it. Chrome has a bug where it will not show it if it is the problem. Commented Sep 16, 2013 at 18:25
  • @TheSharpieOne added Firefox headers Commented Sep 16, 2013 at 18:33
  • 1
    What backend are you using? The problem seems to be way you implented CORS support because the error message you get is a reply from the server telling you that the origin you come from isnt allowed. Commented Sep 16, 2013 at 19:15

3 Answers 3

4

I had a similar issue. Tried all the suggestions I could see online yet none worked. Not until I had to manually set the Content-Type to application/x-www-form-urlencoded before making the post request.

You can do this via:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
Sign up to request clarification or add additional context in comments.

Comments

2

I've solved this: You are making a Cross-Origin Request, from http to https.

This is not described in the spec, but you can test this in chrome, which ignores the problem.

You must stick to all http or all https.

Good luck.

Comments

0

Unless the server you are posting to accepts AngularJS OPTIONS requests, there's no way you can do a POST from your server. You need to configure and setup your server to accept this requests; depending on the language, there are many guides that can be found through CORS server setup +LANGUAGE.

A less known trick that some API's use is to use JSONP. AngularJS JSONP calls can be done like this:

$http.jsonp('https://api.endpoint.com/post-json?id=ID-KEY&callback=JSON_CALLBACK')
 .success(function(data, status) {... })

This also requires some work from the server, but if you are trying to consume a third party, might be your option.

Update: You might be missing Access-Control-Allow-Methods:POST, GET, OPTIONS, PUT, DELETE in your Server Response Headers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.