0

JSONP request in angularjs fails

When running the following angularjs code to retrieve JSONP data it does work fine when making a request to https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero or http://code.jsontest.com?callback=JSON_CALLBACK. But when making a request to my local (bash or monkey) webserver it fails.

The returned content of my local webserver is stored in wcontent

export wcontent='JSON_CALLBACK([ 
    {"msg":"Message one"}, 
    {"msg":"Message two"} 
    ]);'

The bash script webserver code is

while true; do cat <<EOF | nc -l 8024 ; done
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Type: application/javascript; charset=ISO-8859-1
Vary: Accept-Encoding
Date: `date`
Server: Google Frontend
Cache-Control: private
Content-Length: ${#wcontent}

${wcontent}
EOF

When requesting the url through firefox, a HTTP 200 with normal response header is returned. The response is also normal and recognized as js (javascript), which is correct for JSONP data.

The following angularjs code is used.

function messagesController ($scope,$http,$templateCache) {

    $scope.fetch = function() {

        console.log("messagesController FETCH Method:" + $scope.method + "  Url:"  + $scope.url ) ;

        $scope.code = null;
        $scope.response = null;

        $http({method: $scope.method, url: $scope.url, cache: $templateCache, timeout: 5000}).
            success(function(data, status) {
                $scope.status = status;
                $scope.data = data;
                $scope.msgs = $scope.data;
                console.log("Fetch SUCCESS ") ;
                console.log("method "+ $scope.method ) ;
                console.log("status " + status) ;
                console.log("data") ;
                console.dir(data) ;
            }).
            error(function(data, status, headers, config) {
                $scope.data = data || "Request failed";
                $scope.status = status;
                console.log("Fetch ERROR") ;                  
                console.log("method " + $scope.method) ;
                console.log("data") ;
                console.dir(data) ;
                console.log("Status:" + status ) ;
                console.log("Headers" + headers) ;
                console.dir(headers) ;
                console.log("config") ;
                console.dir(config);

            });
        };

    $scope.updateModel = function(method, url) {
    $scope.method = method;
    $scope.url = url;
};

When making a request to any of the previously mentioned external JSONP objects the JSONP object is retrieved. When the request is made to the (bash or monkey) webserver it fails with the following console logging;

 messagesController FETCH method:JSONP Url://http://127.0.0.1:8024/?callback=JSON_CALLBACK
 Fetch ERROR
 method JSONP
 data
     undefined
 Status: 0
 Headersfunction(name) {
 "use strict";

     if (!headersObj) headersObj = parseHeaders(headers) ;

     if (name) {
        return headersObj[lowercase(name)] || null ;
     }

     return headersObj;
 }
 [object Function] 
 "config"
 [object Object]

So it returns a HTTP status code 0. And based on the output header there seems to be something with the HTTP header.

What i have tried;

  • I have tried different combinations of HTTP headers.
  • 2 different versions of webservers
  • used external ip-address instead of localhost
  • used hostname instead of ip-address
  • AngularJS 1.2.1, 1.2.26 and 1.3.2

Anyone who can help me out on this ?

20141115 Added HTTP Headers made using tcpdump when request made from angularjs

Request

GET /?callback=angular.callbacks._1 HTTP/1.1
Host: reddipped.localdomain:8024
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://localhost:7002/console/console.portal?_nfpb=true&_pageLabel=HomePage1
Connection: keep-alive

Reply

HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Type: application/javascript; charset=ISO-8859-1
Vary: Accept-Encoding
Date: Sat Nov 15 23:14:52 CET 2014
Server: Google Frontend
Cache-Control: private
Content-Length: 91

JSON_CALLBACK([ 
        {"msg":"Message one"}, 
        {"msg":"Message two"} 
        ]);

For the benefit of others, here a rewritten bash http server to be able to test JSONP requests made using angularjs. See the answer from Roman L for the explanation.

#!/bin/bash
#
#

# reads JSON Data
function loadJSON(){

        echo '[
                {"msg":"Message 1"},
                {"msg":"Anonco 2"},
                {"msg":"Avis 3"}
        ]'

}

# proces HTTP JSONP request
function procesRequest() {

   # Read first line of HTTP request,this line has the format
   # "Method SP Request-URI SP HTTP-Version CRLF"
   read request
   # Get callback url variable value which is requested JSONP callback 
   # function name 
   callback=$(echo $request | sed -r 's/.*callback=(.*) .*/\1/g ; /GET/{q100}')
   if [ "$?" -eq "100" ] || [ -z "$callback" ]; then
     callback="JSONP_CALLBACK"
   fi
   # Create response body
   wcontent=${callback}"("$(loadJSON)");"

   # Compose response
cat <<EOF
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Type: application/javascript;
Date: `date`
Server: Reddipped Bash
Cache-Control: no-cache
Content-Length: ${#wcontent}

${wcontent}
EOF

  ## Clearing buffer
  while read -t 1; do
    true
  done

}

# Listen Port
PORT=8024

# Setup named pipe to pass HTTP response back to netcat
TMP=`mktemp -d`
LOOP=$TMP/pipe.loop
REQ=$TMP/pipe.req
RPY=$TMP/pipe.rpy
trap 'rm -rf "$TMP"' EXIT
mkfifo -m 0600 "$LOOP" "$REQ" "$RPY"
sed 's/^/-REQUEST->/' <"$REQ" &
sed 's/^/<--REPLY--/' <"$RPY" &


echo Waiting for HTTP request
nc -r -l $PORT <"$LOOP" | tee "$REQ" | procesRequest | tee "$RPY" >"$LOOP"
echo Send HTTP response
nohup $0

1 Answer 1

1

Angular will replace JSON_CALLBACK in your url with a specific callback name, e.g. cb_0, so the actual request will look like server?callback=cb_0. Your server has to return JSON wrapped into this callback

cb_0([ 
  {"msg":"Message one"}, 
  {"msg":"Message two"} 
])

Try changing callback name in your link and see the response in browser: https://angularjs.org/greet.php?name=Super%20Hero&callback=cb_0

Update:

If I understand your bash code correctly, when you navigate to http://127.0.0.1:8024/?callback=cb_0 you will see this output:

JSON_CALLBACK([ 
  {"msg":"Message one"}, 
  {"msg":"Message two"} 
]);

while you should be seeing cb_0. My guess is that this could be the reason for the error.

4
  • Hi Romain, The request to angularjs.org and code.jsontest.com from angularjs do work. It is the request to one of my local webservers which returns a status code 0. The request is also translated to http://reddipped.localdomain:8024/?callback=angular.callbacks_0 When i make a request using http://reddipped.localdomain:8024/?callback=angular.callbacks_0 or http://reddipped.localdomain:8024/?callback=JSONP_CALLBACK from the browser i get a HTTP 200 and a proper response.
    – pcvnes
    Nov 15, 2014 at 22:05
  • @pcvnes I understand this and I was talking about your local server. Check my update, maybe it will clarify a bit.
    – Roman L
    Nov 16, 2014 at 2:45
  • Hi Roman, Thanks! Now in finally see what i was overlooked. When angularjs makes an HTTP JSONP request the callback url variable specifies the name of the callback function it requests in the response! I rewrote the bash http server to return the JSONP function/object as supplied in the callback variable.
    – pcvnes
    Nov 17, 2014 at 22:27
  • @pcvnes: Great, glad I pushed you in the right direction!
    – Roman L
    Nov 18, 2014 at 0:45

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.