【发布时间】:2012-06-04 12:46:32
【问题描述】:
我有一个包含 jqGrid 插件的简单 HTML 文件。我正在使用 jqGrid 插件在我的 HTML 页面中有一个树形网格。
现在,我正在尝试在 node.js 服务器中托管这个 HTML 文件。我的 server.js 看起来像这样
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (request, response) {
console.log('request starting...');
var filePath = '.' + request.url;
console.log('filePath : '+filePath);
if (filePath == './')
filePath = './tree.html';
var extname = path.extname(filePath);
console.log('extname : '+extname);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
}
path.exists(filePath, function(exists) {
if (exists) {
fs.readFile(filePath, function(error, content) {
if (error) {
response.writeHead(500);
response.end();
} else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
} else {
response.writeHead(404);
response.end();
}
});
}).listen(8125);
到目前为止,我可以在浏览器中显示我的 HTML 内容 [http://localhost:8125/]
我的部分 HTML(tree.html) 文件如下所示
jQuery("#treegrid").jqGrid({
url: 'tree.json',
datatype: 'json',
//mtype: 'GET',
colNames: [/* "ID", */"Col 1", "Col 2",.. ],
colModel: [/* {
name: 'id',
index: 'id',
width: 1,
hidden: true,
key: true
}, */{ ...
如果您注意到,我已将“tree.json”指定为 URL 属性以加载树形网格。那只是读取一个静态文件来加载带有示例数据的树形网格。
问题: 现在,当我尝试使用 [http://localhost:8125/] 访问我的 HTML 文件时 我收到 [http://localhost:8125/tree.json] 的 404 Not Found 错误
快速解决方案:我可以指定文件'tree.json'的相对路径并且它可以工作。
我的 HTML 文件 tree.html 和 tree.json 都在同一个目录 (/tree) 中,我从命令提示符(终端) 像这样
tree> node server.js
我想知道我可以将 tree.json 放在哪里,以使我的 HTML 按预期工作。
如有任何疑问,请随时提出。
提前致谢
【问题讨论】:
-
您在代码中包含了
console.log('filePath : '+filePath);。你是否在控制台中获得了一些关于tree.json请求的信息? -
仅供参考,我的 tree.json 的内容看起来像这样 { "page": 1, "total": 1, "records": 2, "rows": [] } 并且 console.log 显示 [localhost:8125/… 404 Not Found。
-
我认为错误“404 Not Found”表示您的文件路径有问题,而不是文件内容。
-
@Oleg 可以看到console.log语句有URL和一些额外的查询参数,这些参数是jqGrid插件添加的吗?如果是这样,那我该如何摆脱它?我可以发布我的 jqGrid 设置(属性)。它不是寻找 tree.json,而是寻找 tree.json?blah..。 conole.log 说请求开始... filePath : ./tree.json?_search=false&nd=1338374206180&rows=20&page=1&sidx=&sord=asc extname : .json?_search=false&nd=1338374206180&rows=20&page=1&sidx=&sord=asc
-
请在下面阅读我对您的问题的回答。当我写上面的评论时,我稍后再写它。你使用
var filePath = '.' + request.url;所以filePath应该以'.'开头,这是我看到修复错误“404 Not Found”的主要问题。 jqGrid 代码和tree.json的内容应该与“未找到”错误无关。
标签: html json node.js jqgrid treegrid