简体   繁体   中英

Undefined HTTP GET Request Interpreted by Node.js Server

I am having an issue with my Node.js application where I am sending an http get request through an ajax call client-side, I am then receiving the request server-side, and trying to use the data sent through the get request. My issue is that the server says that the request is undefined. I have absolutely no idea why this is the case as I am doing other similar requests on other pages and they work fine.

Here is my error message:

/var/www/html/AdminExtension/extension/extension/node_modules/find/index.js:35
          throw err;
                ^
Error: ENOENT, lstat '/path/to/project/undefined'

The "undefined" bit is what is supposed to be the rest of the path retrieved from the request.

Here is my relevant app.js code:

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"));

Server-side browse.js code:

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.");
                    });
}

And the client-side ajax request:

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
    }
});

I appreciate any input.

The problem is probably in your checkData function:

function checkData(data) {
    console.log(JSON.stringify(request.body));
    return data;
}

It receives only data and you use the request object - it's not accessible in its context.

You can add another parameter called request to that function:

function checkData(data, request) {
    console.log(JSON.stringify(request.body));
    return data;
}

And send it the request object:

checkData(request.body.filePath, request)

UPDATE

After you've updated your question your original problem appeared.

I geuss the undefined problem you got there is because you're accessing the request body - a request has a body with parameters if it's a POST request ( GET requests has only a url and headers).

Try changing your client side ajax call from type : "GET" to type : "POST" and update your nodejs:

app.get('/browse/file/info', browse.getFileInformation);

to

app.post('/browse/file/info', browse.getFileInformation);

I would also recommend to get a file path with __dirname + '/path' to avoid problems.

As it turns out, I needed to use

request.query.filePath

instead of

request.body.filePath

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM