onlyMe
onlyMe

Reputation: 127

Node.js: Redirect and send page at once

I'm trying to build simple server for HTML pages in Node.js. My problem is, when I navigate to (for example) http://localhost:8080/someDirectory, browser thinks that someDirectory is file (in reality, it is interally redirected to someDirectory/index.html).

So when I do <script src="./script.js"></script>, it tries to use http://localhost:8080/script.js, instead of http://localhost:8080/someDirectory/script.js.

Only solution I can think of is to redirect browser to /someDirectory/ (with slash at the end). Then, the browser correctly understands that it is directory and not file.

My problem is, I don't want to make my server slow, because of double request (client gets redirected, sends another request, and then finally gets the webpage). Is there any posibility to send send page and just notify the browser of change, instead of using 302 header to redirect?


EDIT: When I visit some page running on Apache server, when I enter http://localhost/someDirectory, the trailing slash get automatically appended. I'm just curious how it is done (no additional PHP or javascript).

Upvotes: 1

Views: 156

Answers (2)

Ryan Wheale
Ryan Wheale

Reputation: 28380

I recommend using history.replaceState (MDN). This will work in most modern browsers (most users) but not in older browsers. Since older browsers are dwindling, it should become less of a problem as time moves on. This should do the trick - you will need to paste it directly in your HTML markup for this to work:

if ( !window.location.pathname.match(/\/$/) ) {
    if ( window.history && window.history.replaceState ) {
        window.history.replaceState(null, null, window.location.pathname + '/');
        document.write('<script src="./script.js"></script>');
    } else
        window.location.replace( window.location.pathname + '/');
} else {
    document.write('<script src="./script.js"></script>');
}

Upvotes: 0

Brad
Brad

Reputation: 163752

No, it's not possible, and wouldn't even be the right solution. You can certainly send content with a redirect, but it's pointless because the browser won't display it... it will immediately follow the redirect.

If you want /someDirectory/, that is different than /someDirectory. You must redirect.

Upvotes: 1

Related Questions