learnyounode icon indicating copy to clipboard operation
learnyounode copied to clipboard

JSON API server works but reports FAIL?

Open guivho opened this issue 10 years ago • 0 comments

My solution works as exoected: if I launch e.g. node mysolution 34444, and point my browser to http://http://localhost:34444/api/parsetime?iso=2015-08-30T08:05:35.655Z I get a nice {"hour":10,"minutes":5,"seconds":35} answer. Same for the unixtime api.

But learnyounode complains Error connecting to http://localhost:34444/api/parsetime?iso=2015-08-30T08:19:34.528Z: Parse Error and Error connecting to http://localhost:34444/api/unixtime?iso=2015-08-30T08:19:34.528Z: Parse Error

Here's my solution:

    const http = require('http')
        , url = require('url');

    function hms(time) {
        return {
            hour: time.getHours(),
            minutes: time.getMinutes(),
            seconds: time.getSeconds()
        };
    }

    function unx(time) {
        return {
            unixtime: time.getTime()
        };
    }

    var server = http.createServer(function listener(request, response) {
        var parsedUrl = url.parse(request.url, true);
        var time = new Date(parsedUrl.query.iso);
        var reply;

        if(/^\/api\/parsetime/.test(request.url)) {
            reply = hms(time);
        } else if (/^\/api\/unixtime/.test(request.url)) {
            reply = unx(time);
        }

        if(reply) {
            response.writeHead(200, {'content-type}':'application/json'});
            response.end(JSON.stringify(reply));
        } else {
            response.writeHead(400);
            response.end();
        }
    });

    server.listen(Number(process.argv[2]));

Please advise,

Guido

guivho avatar Aug 30 '15 08:08 guivho