Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express adds trailing slash

Tags:

node.js

I have tried several ways of serving up a static directory. Here is a simple way I am doing this.

var app = express();

app.all('*', express.static('./public'));

module.exports = app;

// run the server
http.createServer(app).listen(8080);

I have several other configurations like:

app.use('/', express.static('./public'));

There is an index.html file in the public directory that gets served up fine. The only thing in the HTML file is a request for a JavaScript file. When that request gets made, express throws a 301 redirect, and adds a trailing slash.

Here is the HTML:

<script type="text/javascript" src="/dist/bundle.js"></script>

Here is the network request.

enter image description here

Any help is appreciated.

like image 596
David Starr - Elegant Code Avatar asked Jan 20 '18 23:01

David Starr - Elegant Code


People also ask

How do you fix a trailing slash?

A 301 redirect is the best way to resolve duplicate content issues caused by trailing slashes. If you're just fixing one page, you'd redirect the duplicate copy to the version that matches your chosen URL structure. Most trailing slash issues however, affect many pages across a website.

Is trailing slash required?

A trailing slash is a forward slash (“/”) placed at the end of a URL such as domain.com/ or domain.com/page/. The trailing slash is generally used to distinguish a directory which has the trailing slash from a file that does not have the trailing slash. However, these are guidelines and not requirements.

What does Express () method do?

Express provides methods to specify what function is called for a particular HTTP verb ( GET , POST , SET , etc.) and URL pattern ("Route"), and methods to specify what template ("view") engine is used, where template files are located, and what template to use to render a response.

Can Express be used for frontend?

Lesser Development Time: Express uses Javascript for both backend and frontend development. Thus, developers can generate codes faster without the need to learn a new language.


2 Answers

You can enable strict route mode and use a route middleware (https://stackoverflow.com/a/15773824/781251)

http://expressjs.com/en/api.html

const router = express.Router({ strict: true })
like image 59
Eduardo Stuart Avatar answered Oct 23 '22 04:10

Eduardo Stuart


This means the asset can't be found. It renders a 404 response.

like image 25
Bram z Avatar answered Oct 23 '22 05:10

Bram z