Unexpected token colon JSON after jQuery.ajax#get

前端 未结 2 848
刺人心
刺人心 2020-11-22 16:44

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

相关标签:
2条回答
  • 2020-11-22 17:18

    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!"
        });
    });
    
    0 讨论(0)
  • 2020-11-22 17:30

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

    0 讨论(0)
提交回复
热议问题