我的 Node.js 应用程序出现问题,我通过 ajax 调用客户端发送 http get 请求,然后在服务器端接收请求,并尝试使用通过 get 请求发送的数据。我的问题是服务器说请求未定义。我完全不知道为什么会这样,因为我正在其他页面上执行其他类似的请求并且它们工作正常。
这是我的错误信息:
/var/www/html/AdminExtension/extension/extension/node_modules/find/index.js:35
throw err;
^
Error: ENOENT, lstat '/path/to/project/undefined'
“未定义”位应该是从请求中检索到的路径的其余部分。
这是我的相关 app.js 代码:
var express = require('express');
var MemoryStore = require('connect').session.MemoryStore;
var app = express();
app.set('port', process.env.PORT || 3333);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('view options', {layout: false});
app.use(require('morgan')('dev'));
app.use(require('body-parser')({ keepExtensions: true}));
app.use(require('cookie-parser')());
app.use(require('express-session')({ secret: '12345678910', store: new MemoryStore({ reapInterval: 600000}) }));
app.use(require('method-override')());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.use(express.static(path.join(__dirname, '/public')));
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET');
next();
});
// Routes for browsing directories and listing contents
var browse = require('./routes/general/browse');
app.get('/browse/file/info', browse.getFileInformation);
app.listen(app.get("port"));
服务器端browse.js代码:
var path = require('path');
var fs = require('fs');
exports.getFileInformation = function(request, response) {
var filePath = "/folder1/folder2/" + request.body.filePath;
console.log('*' + filePath + '*');
checkFileInfo(
filePath,
function(err, fileInfo) {
if (err)
console
.log("An error has occured when trying to retrieve the file information: "
+ err);
else
response.send(fileInfo);
});
};
function checkFileInfo(filePath, callback) {
fs
.lstat(
filePath,
function(err, stats) {
if (err)
return callback(err);
else if (stats && stats.isFile()) {
var fileInfo = {};
fileInfo.size = stats.size;
fileInfo.created = stats.ctime;
fileInfo.modified = stats.mtime;
fileInfo.accessed = stats.atime;
callback(null, fileInfo);
} else
return callback("The path provided did not lead to an accessible file.");
});
}
和客户端ajax请求:
var obj = {
filePath : "/relative/path/this_is_a_file.txt"
};
$.ajax({
type : "GET",
url : serverUrl + '/browse/file/info',
data : obj,
dataType : 'json',
success : function(fileData) {
// Do something else
}
});
我很感激任何意见。