Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs/Expressjs javascript: get where request came from

I am using nodejs with the expressjs module to create a webserver. My current setup is this

var express = require("C:/Program Files/nodejs/node_modules/express")
var app = express();
var server = require('http').createServer(app).listen(80);
var io = require('C:/Program Files/nodejs/node_modules/socket.io').listen(server, {log:false});
var path = require("path");
fs = require("fs");

is there a way using

app.use(function(req,res,next){
//code
})

to get where a request came from? Eg, if on an html page, you have the script tag

<script src="test.js"></script>

it sends a request to retrieve test.js, can I use the req argument to see that the request for test.js came from the html page and get the full filepath of the html page?

EDIT: I'm trying to write a function that serves the correct index file (index.html/.htm/.php etc if you just enter a directory into the url ("localhost/tests/chat/"), but the problem then is, when it requests the javascript file from the index page, it goes back 1 directory too far (searches for "localhost/tests/test.js" instead of "localhost/tests/chat/test.js"), and only works if you directly type the filename into the url ("localhost/tests/chat/index.html"). My function:

app.use(function(req,res,next){
    var getFullPath = path.join("public",req.path);
    console.log(req.path);
    if (fs.existsSync(getFullPath)) {
        if (fs.statSync(getFullPath).isDirectory()) {
            getFullPath = path.join(getFullPath,"index.html");
        }
        res.sendfile(getFullPath);
    } else {
        res.send("404 Not Found");
    }
});

I realise you can use

app.use(express.static(__dirname + '/public'));

but this creates a problem for me with my custom php parser module so that's not really an option

like image 465
Greg Hornby Avatar asked Dec 01 '25 02:12

Greg Hornby


1 Answers

I was able to use req.headers.referer to get where the javascript file was being asked from and therefore point to the correct location of the javascript file.

getFullPath = path.join("public",req.headers.referer.split(req.host)[1],path.basename(req.path));
like image 93
Greg Hornby Avatar answered Dec 03 '25 18:12

Greg Hornby