8

I have created a minimalist API on nodejs which return data in JSON format.

But every time I try to make a ajax#get call and pass my API as URL, I will get an error and judging from Chrome, I'm getting a "Unexpected token :" error;

here the server code in nodejs + express:

var
 http    = require( 'http' ),
 express = require( 'express' ),
 app      = express(),
 server  = http.createServer( app );

app.get( '/', function( req, res ) {
    console.log( 'req received' );
        res.setHeader('Content-Type', 'application/json');
    res.end( JSON.stringify({
    Name : "Tom",
    Description : "Hello it's me!"
    }) );

});

server.listen(3000, function() {
    console.log( 'Listening on 3000' );
});

The JSON returned from "/" is: {"Name":"Tom","Description":"Hello it's me!"}.

Here is my call from the client js:

$.ajax({
    url: findUrl,
    type: 'get',
    dataType: 'jsonp',
    success: function ( data ) {
        self.name( data.Name );
        self.description( data.Description );
    },
    error: function( jqXHR, textStatus, errorThrown ) {
        alert(errorThrown);
    }
});

When plotting the error I get: "jQuery111108398571682628244_1403193212453 was not called"

Can someone help me?

I know this question has been asked already but I haven't manage to find a solution which fix my program.

nyedidikeke
  • 6,899
  • 7
  • 44
  • 59
K. L.
  • 654
  • 2
  • 10
  • 21
  • Check your `dataType` - [$.ajax()](http://api.jquery.com/jquery.ajax/) – Andreas Jun 19 '14 at 16:00
  • @Andreas : I guess you refer to "jsonp", I changed it to "json". I am now getting "XMLHttpRequest cannot load http://localhost:3000/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access." how can I fix this ? – K. L. Jun 19 '14 at 16:09

2 Answers2

9

To support JSONP requests, the server will have to include the P, or "Padding," in the response.

jQuery111108398571682628244_1403193212453({"Name":"Tom","Description":"Hello it's me!"})

The syntax error, "Unexpected token :", is because JSONP is parsed as JavaScript, where {...} also represents blocks. It just takes advantage of JSON and JavaScript's similar syntax to define the data being passed to a global function call.

By default, jQuery will include a callback query-string parameter with the name of the function:

var callback = req.query.callback;
var data = JSON.stringify({
    Name : "Tom",
    Description : "Hello it's me!"
});

if (callback) {
    res.setHeader('Content-Type', 'text/javascript');
    res.end(callback + '(' + data + ')');
} else {
    res.setHeader('Content-Type', 'application/json');
    res.end(data);
}

ExpressJS also includes res.jsonp() that already implements this condition:

app.get( '/', function( req, res ) {
    console.log( 'req received' );

    res.jsonp({
        Name : "Tom",
        Description : "Hello it's me!"
    });
});
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
-3

You want to use dataType: "json" instead of "jsonp"

Dan Putman
  • 48
  • 5
  • there are different reasons why you want to use jsonp, one example is to be able to call across different domains – Mahshid Zeinaly Apr 08 '15 at 21:40
  • agreed, jsonp is for CORS, you can't just use json if you need to make a cross domain async request via javascript. – Karl Jun 30 '15 at 20:22
  • 1
    JSONP is not for CORS. JSONP is the hack we used before CORS was developed and supported by browsers. – Quentin Jul 31 '15 at 09:36
  • Thank you for clarifying that's what I meant. JSONP is for when you cannot use CORS. – Karl Aug 05 '15 at 19:38