I am learning nodeJS and I have this syntax error which I don't understand. Can someone point out what is the syntax error, why I am getting it, and how do I bypass it?
var http = require('http');
var url = require('url');
var server = http.createServer(function(req,res) {
if (req.method == 'POST') {
return res.end("Only get requests");
}
var st = url.parse(req.url,true);
if (st.indexOf("parsetime") > -1) {
var time = st.substring(st.indexOf("iso"));
var date = new Date(time);
var out = '{
"hour":'+date.getHours()+',
"minute":'+date.getMinutes()+',
"second":'+date.getSeconds()+',
}';
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(out);
} else if (st.indexOf("unixtime") > -1) {
var time = st.substring(st.indexOf("iso"));
var date = new Date(time);
var out = "{
'unixtime':"+date.getTime()+"
}";
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(out);
} else {
return res.end("404");
}
});
server.listen(process.argv[2]);
The syntax error is on line 11 : " var out = '{ "
Remove the single quotes from here:
var out = '{
"hour":'+date.getHours()+',
"minute":'+date.getMinutes()+',
"second":'+date.getSeconds()+',
}';
Change the above to:
var out = {
"hour": date.getHours(),
"minute": date.getMinutes(),
"second": date.getSeconds(),
};
Or if I may be mistaken for the string to contain a JSON object, you need to do declare the out
that way and stringify using:
out = JSON.stringify(out);
The problem is that you tried to have a multi-line string, which you can't do like that in JavaScript. It is probably easier to do it like this:
var out = '{';
out+='"hour":'+date.getHours(),
out+='"minute":'+date.getMinutes(),
out+='"second":'+date.getSeconds()
out+='}';
Or, even easier, just define the object, then use JSON.stringify()
to turn it into a string:
var outObj = {
hour:date.getHours(),
minute:date.getMinutes(),
second:date.getSeconds()
};
var obj=JSON.stringify(outObj);
This just defines a normal object, then turns it into JSON
Remove quotes
var out = {"hour":'+date.getHours()+',
"minute":'+date.getMinutes()+',
"second":'+date.getSeconds()+',
};