在浏览器中使用Node.JS在没有文件扩展名的情况下显示json文件
我已经使用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");
我怎样才能做到这一点? 我应该使用路线/快递吗? 有人有什么build议吗?
先谢谢你!
干杯,弗拉德
您的问题可能是由于内容types。 扩展名为.json可能会触发您的浏览器将其作为application/json
。 所以如果你删除扩展名,你需要添加适当的Content-Type
。
鉴于你已经在使用内容types,你不能只是在这里添加它,并确保你为jsons编写types?
var contentTypesByExtension = { '.html': "text/html", '.css': "text/css", '.js': "text/javascript", '.json': "application/json" // <--- };
我刚刚使用大锤的方法现在评论这个代码片段:
if(!exists) { res.writeHead(404, {"Content-Type": "text/plain"}); res.write("404 Not Found\n"); res.end(); return; }
现在它可以调用: http://localhost:8888/Test
干杯,弗拉德
- 如何从通用的JavaScript引用一个React类
- Nodejs服务器 – 通过使循环迭代asynchronous来提高性能
- 读文件和string平等问题
- Mongolab nodejs拓扑被破坏
- 护照通过Google reCaptcha进行身份validation
- 什么函数在NodeJs和JS中放入EventLoop
- node.js和浏览器之间JavaScript的语法差异是什么?
- 你如何从Mac完全删除Ionic和Cordova的安装?
- WebSocket连接到'wss:// localhost:44300 / Home / websocketcon'失败:WebSocket握手期间出错:意外的响应代码:404