javascript - Display json file in Browser using Node.JS without file extension -
i have made server using javascript , node.js shows json file in browser.
however, call site http://localhost:8888/test.json
without extension. example just: http://localhost:8888/test
here server code:
var http = require("http"), url = require("url"), path = require("path"), fs = require("fs") port = process.argv[2] || 8888; file = (__dirname + '/test.json'); http.createserver(function(req, res) { var uri = url.parse(req.url).pathname, filename = path.join(process.cwd(), uri); var contenttypesbyextension = { '.html': "text/html", '.css': "text/css", '.js': "text/javascript", '.json': "application/json" //edited due answer - still no success :( }; path.exists(filename, function(exists) { if(!exists) { res.writehead(404, {"content-type": "text/plain"}); res.write("404 not found\n"); res.end(); return; } fs.readfile(file, 'utf8', function (err, file) { if (err) { console.log('error: ' + err); return; } file = json.parse(file); console.dir(file); var headers = {}; var contenttype = contenttypesbyextension[path.extname(file)]; if (contenttype) headers["content-type"] = contenttype; res.writehead(200, headers); res.write(json.stringify(file, 0 ,3)); res.write res.end(); }); }); }).listen(parseint(port, 10)); console.log("json parsing rest server running at\n => http://localhost:" + port + "/\npress ctrl + c exit , leave");
how can that? should use routes/express? have suggestions?
thank in advance!
cheers, vlad
your problem due content type. having extension .json triggering browser consume application/json
. if remove extension need add proper content-type
.
given playing around content types, can't add here, , make sure write type jsons well?
var contenttypesbyextension = { '.html': "text/html", '.css': "text/css", '.js': "text/javascript", '.json': "application/json" // <--- };
Comments
Post a Comment