Coty Embry
Coty Embry

Reputation: 978

Express js routing is downloading file and not rendering it

I am trying to implement a router on the server side with node.js and express.js. I want to serve a file statically, but I already got this to work for a index.html file I created. No problems there.

My setup has tons of fileName.csp files (i.e. they end in .csp). Anyways, when I try to access a .csp file in the browser (inside it is really just a .html page - but the server side language must have it as a .csp file extension) but when I try to access it, the browser (google chrome) downloads the .csp file instead of rendering it!

I could really use some help since I'm new to all of this.

the line of code that is allowing the download of the .csp file, the code that exposes the directory where the .csp files live, is

app.use('/static', express.static('D:/CACHESYS/CSP/cah/'));

below is pretty much the whole snippet of code

var http = require('http');
var express = require('express');
var app = express();

app.use('/static', express.static('D:/CACHESYS/CSP/cah/'));

app.listen(3000, function() {
    console.log('listening on port 3000');
})

app.get('/home', function(request, response) {
    response.end('going to /home');
})

app.get('/csp/cah/MARS.csp', function(request, response) {
    response.end('Trying to navigate to /csp/cah/MARS.csp');
})

p.s. the actual file path that is being downloaded is

D:/CACHESYS/CSP/cah/fileName.csp

just to give some more context for the question.

any help is appreciated

thanks!

Upvotes: 2

Views: 2594

Answers (1)

MrWillihog
MrWillihog

Reputation: 2646

You need to tell express what content type a .csp file is. You can do this with the following line:

express.static.mime.define({
    'text/html': ['csp']
});

Although, if the file is an HTML file, it should probably have the .html extension. Also, if you are simply serving static files it is good practice to use an HTTP server like nginx or Apache to do that, rather than Node.js.

The reason this works is express will set the header Content-Type: text/html. This tells the browser it is HTML and it should render it as such. By default if a browser comes across a content type it doesn't recognise, it simply downloads it.

Upvotes: 2

Related Questions