使用Node.JS在浏览器中显示json文件,不带文件扩展名

时间:2014-06-27 12:09:05

标签: javascript json node.js

我使用javascript和Node.js创建了一个服务器,在我的浏览器中显示了一个JSON文件。

但是,我想在没有附加信息的情况下致电网站http://localhost:8888/Test.json。 例如:http://localhost:8888/Test

这是我的服务器代码:

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");

我该怎么做? 我应该使用路线/快递吗? 有人有什么建议吗?

提前谢谢!

干杯,弗拉德

2 个答案:

答案 0 :(得分:1)

您的问题可能是由于内容类型造成的。扩展名.json可能会触发您的浏览器将其用作application/json。因此,如果您删除了扩展程序,则需要添加正确的Content-Type

鉴于您已经在使用内容类型,您是否只需将其添加到此处,并确保您也为jsons编写类型?

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

答案 1 :(得分:0)

我现在只是使用了大锤方法来评论此代码片段:

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

现在只需拨打电话:http://localhost:8888/Test

干杯,弗拉德

相关问题