Question

I'm trying to get a response from a web service using Angular JS, which I can perfectly reach via my shell using a simple curl command:

curl --header "Content-type: application/json" --request POST 
     --data '{"username": "name", "password": "pwd"}' 192.168.2.1:9000/ws/login


However, when I try to reach it using Angular with an $http.post I experience some "funny" behaviour.

While my data are:

    var url = "192.168.2.1:9000/ws/login"
    var postData = {
        username: un,
        password: pwd
    }


I've tried both postData as a JSON object and as a stringified JSON

Using a call like this:

    $http.post( url, postData ).
        success(function(data) {
        console.log(data)
        }).
        error(function(data, status, headers, config) {
            console.log(data, status, headers, config)
        })

or even

    $http({
        url: url,
        method: 'POST',
        data: JSON.stringify(postData),
        headers: {'Content-type': 'application/json'}
        }).
        success(function(data, status, headers, config) {
            console.log('Success: ', data, status, headers, config)

        }).
        error(function(data, status, headers, config) {
            console.log('Error: ', data, status, headers, config)

        })

Simply do nothing.
Nothing at all!


Prepending an http:// to the url instead, gives me:

OPTIONS http://192.168.2.1:9000/ws/login 404 (Not Found) angular.js:7073
OPTIONS http://192.168.2.1:9000/ws/login Origin http://localhost:9000 is not allowed by Access-Control-Allow-Origin. 

I'm really really lost... any advice would be much appreciated!

Was it helpful?

Solution

I've managed to get a CORS setup up & running.

The server side for my case was far from trivial, since we're using Play! framework and modern browsers sends an OPTION method before sending the real POST method, to be somewhat "pre-authorized" to send the CORS request.

As stated in http://better-inter.net/enabling-cors-in-angular-js/ I had to add

        $http.defaults.useXDomain = true;

prior of the actual $http.post, but I didn't had to delete the 'Content-Type' header


Should you ever use a similar setup, I would reccomend taking a look on these resources:

Play 2.0.1 and setting Access-Control-Allow-Origin
Play! 2.0 easy fix to OPTIONS response for router catch-all?

OTHER TIPS

As Adam said!

If you are using apache:

 Header set Access-Control-Allow-Origin:  http://domain.com, http://localhost/

or just

Header set Access-Control-Allow-Origin: *

Do this only for testing. For production limit the origin to only your domain.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top