我使用 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");

我怎样才能做到这一点?
我应该使用路线/ express 吗?
有人有什么建议吗?

先感谢您!

干杯,弗拉德

最佳答案

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

鉴于您已经在使用内容类型,您不能在此处添加它,并确保您也为 jsons 编写类型吗?

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

关于javascript - 使用没有文件扩展名的 Node.JS 在浏览器中显示 json 文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24451503/

10-12 00:32
查看更多