Display json file in browser using Node.JS without file extension

I created a server using javascript and Node.js that shows a JSON file in my browser.

However, I would like to name the site http://localhost:8888/Test.jsonwithout extension. For example, simply:http://localhost:8888/Test

Here is my 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 to 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 to exit and leave");

How can i do this? Should I use routes / express? Does anyone have any suggestions?

Thank you in advance!

Greetings, Vlad

+4
source share
2 answers

I just applied the sledgehammer method with comments on this piece of code:

if(!exists) {
      res.writeHead(404, {"Content-Type": "text/plain"});
      res.write("404 Not Found\n");
      res.end();
      return;
    }

Now it works to call simply: http://localhost:8888/Test

Greetings, Vlad

0
source

, . , .json application/json. , , Content-Type.

, , , jsons?

  var contentTypesByExtension = {
    '.html': "text/html",
    '.css':  "text/css",
    '.js':   "text/javascript",
    '.json': "application/json" // <---
  };
+1

Source: https://habr.com/ru/post/1546300/


All Articles