maryam maryam - 1 year ago 77
Node.js Question

SyntaxError: Unexpected token u or [SyntaxError: Unexpected end of input]

this is my code i use promises

var http = require("http");
function webFunc(req, res){
var p = getData();
p.then(function(data) {
// var jsonData = JSON.parse(data);
// console.log(JSON.parse(data))
res.send(JSON.parse(data));
}).catch(function(err) {
console.log(err);
})
}
function getData(){
var prom=new Promise (function(resolve,reject){
http.get(url,function(res) {
var data = "";
res.on("data", function(chunk) {
data += chunk;
resolve(data);
return;
})
res.on("error", function(error) {
console.log("Got error: " + error.message);
reject(error);
});
});
})
return prom;
}


when i run route without set JSON.parse like this

res.send(data);


I got half data or all data on each time run
if i set JSON.parse like this

res.send(JSON.parse(data));


I got this error

[SyntaxError: Unexpected token u]
or this
[SyntaxError: Unexpected end of input]


the result of data should contain 8 objects of info like this
i did this commands

console.log(data)
console.log("typeof data",typeof data)
i got this
{"days":{"location":{"id":11,"name":"city","resultinfo":{"info":[{"d":"2017-02-07","tt":15,"ss":"39"
typeof data string


How i can solve this problem

Answer Source

You're using the data too soon. Refer to the example in the documenation of http.get:

let rawData = '';
res.on('data', (chunk) => rawData += chunk);
res.on('end', () => {
  try {
    let parsedData = JSON.parse(rawData);
    console.log(parsedData);
  } catch (e) {
    console.log(e.message);
  }
});

You want to use the data on the end event, not on the data event. You're processing only part of the data if you resolve the project as of the first data event.

So (note *** lines):

function getData() {
    var prom = new Promise(function(resolve, reject) {
        http.get(url, function(res) {
            var data = "";
            res.setEncoding('utf8');              // See note below
            res.on("data", function(chunk) {      // ***
                data += chunk;                    // ***
            })                                    // ***
            res.on("end", function() {            // ***
                resolve(data);                    // ***
            });                                   // ***
            res.on("error", function(error) {
                console.log("Got error: " + error.message);
                reject(error);
            });
        });
    })
    return prom;
}

As Ryan points out, you need the

res.setEncoding('utf8');

indicated above if you want the data chunks as strings rather than as Buffers.


Re your edit:

the result of data should contain 8 objects of info like this

The data you've quoted isn't JSON. In JSON, property names must be in double quotes. To be JSON, it would have to look like this:

{
    "first-days": {
        "location": {
            "id": 11,
            "loc": "city",
            "info": {
            }
        }
    }
}

I've left out bits of your example that just didn't make any sense at all, but you get the gist. More on JSON.org.

Your subsequent edit shows the real thing; what we can see of it looks like valid JSON.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download