在浏览器中使用Node.JS显示json文件,不带文件扩展名
Display json file in Browser using Node.JS without file extension
我使用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");
我该怎么做呢?我应该坐快车吗?有人有什么建议吗?
提前感谢!
欢呼,弗拉德
您的问题可能是由于内容类型。拥有扩展名。json可能会触发浏览器将其作为application/json
消费。因此,如果您删除扩展,您需要添加适当的Content-Type
。
考虑到你已经在玩内容类型,你不能在这里添加它,并确保你为json写的类型?
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-如何读取json文件中的列并将其保存在Javascript数组中
- 在使用Polymer'加载所有json文件后执行方法;s的核心ajax
- 不显示带有本地json文件数据的谷歌地图脚本
- 可以't使用Appcelerator将JSON文件解析为JavaScript中的TableView
- 加载两个具有相同父密钥名称的json文件
- 使用JSON文件中的变量(字符串)填充文本区域
- 动态显示JSON文件内容
- 将JSON转换为放入Sdcard中的CSV文件
- 正在尝试将JSON文件放入JS数组
- 如何检查Json文件更新,如果更新了,则用更新的数据刷新我的页面
- 单击按钮更改加载到表中的JSON文件
- 创建一个包含两个文件 json 的 Angularjs 过滤器
- Multer上传文件+JSON对象
- 使用node.js读取和写入文件(JSON)
- 如何在angularjs中设置变量's值来上传文件json数据
- 向现有文件. Json写入Json,没有“语法错误”
- 如何保存更新json(文件json)与jquery或javascript
- AngularJS:当使用$http请求一个文件(json content)时发生SyntaxError
- 如何简化此代码?将文件json转换为数组json
- 如何从外部文件JSON创建JAVASCRIPT数组