简体   繁体   中英

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

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

However, I would like to call the site http://localhost:8888/Test.json without an extension. For example just: 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 that? Should I use routes/express? Does someone have any suggestions?

Thank you in advance!

Cheers, Vlad

Your problem is probably due to the content type. Having the extension .json is probably triggering your browser to consume it as application/json . So if you remove the extension you need to add the proper Content-Type .

Given that you are already playing around with content types, can't you just add it here, and make sure you write the type for jsons as well?

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

I've just used the sledgehammer method now with commenting this code fragment out:

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

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

Cheers, Vlad

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM