How do I prevent Node.js / Express serving up my a

2019-01-26 05:50发布

问题:

I never thought this would be a problem with Node.js and Express, but on a crazy whim I decided to type into a browser the location of one of the source files in my Node.js Express project - something like:

http://www.mywebsite.com/mynodejsapp/app.js

To my extreme horror, my application's source code popped right up, publicly available for all to see.

So, that aside: how do I stop it in Node.js / Express?

My setup code is pretty straightforward:

var app = express();
app.configure(function() {
    app.use(express.static('/home/prod/server/app/public'));
});
app.listen(8888);

To clarify, this is what my folder structure looks like:

/home/prod/server/
/home/prod/server/app.js
/home/prod/server/public/

All sorts of various files that are intended for public access live under /public. All of my server source code lives under /server/, and my understanding of Express's static folder configuration is that the static folder is the only place that Express happily serves up files from the filesystem from.

Any ideas?

回答1:

From what you posted it really smells like the URL you entered is served by e.g. Apache/nginx/... and you did put your node app within the document root. The answer is simple in this (and any similar) case:

You never put any of your sourcecode files within the document root or another HTTP-accessible folder. In your case, /home/prod/server/app/public should contain only client-side stuff (HTML, CSS, Graphics, (minified) client-side JS) and nginx should not have anything above this folder as its document root.