In: Computer Science
I am trying to use express to get and post time from a url browser. Here is my code:
var express = require('express');
var app = express();
var url = require('url');
function parsetime (time) {
return {
hour: time.getHours(),
minute: time.getMinutes(),
second: time.getSeconds()
};
}
function unixtime (time) {
return { unixtime : time.getTime() };
}
app.get('/', function (req, res) {
var parsedUrl = url.parse(req.url, true);
var time = new Date(parsedUrl.query.iso);
var result;
if (/^\/api\/parsetime/.test(req.url))
result = parsetime(time);
else if (/^\/api\/unixtime/.test(req.url))
result = unixtime(time);
if (result) {
console.log(200, 'OK Success');
res.end(JSON.stringify(result));
} else {
console.log(404, 'Page not found');
res.end();
}
})
app.listen(3000);
however I am getting an error
it is not res.end but it is res.send() fundtion to send response back to client
and another this i have tested the endpoint and also added demo test point for just checking pupose
it is working and please do check my comment
var express = require('express');
var app = express();
var url = require('url');
function parsetime(time) {
return {
hour: time.getHours(),
minute: time.getMinutes(),
second: time.getSeconds()
};
}
function unixtime(time) {
return { unixtime: time.getTime() };
}
app.get('/', function (req, res) {
console.log("in get ////")
var parsedUrl = url.parse(req.url, true);
var time = new Date(parsedUrl.query.iso);
var result;
// an not sure what it test method doing but it is not going to
// if block it always goinf to else
if (/^\/api\/parsetime/.test(req.url))
result = parsetime(time);
else if (/^\/api\/unixtime/.test(req.url))
result = unixtime(time);
console.log("result = "+result);
if (result) {
console.log(200, 'OK Success');
// send with status code
res.send(200, JSON.stringify(result));
} else {
console.log(404, 'Page not found');
// send the json response
res.send(404, {"msg":'page not found'});
}
})
// test endpoint added you can test it by http://localhost:3000/test
app.get('/test', function(req, res){
res.send(200, {"msg":"Helloo"});
})
app.listen(3000);
console.log('Server started on localhost:3000.......');
// OUTPUT
Please do let me know if u have any concern...