简体   繁体   中英

node.js - express - URL and error handling

i'm new to node.js, so please be indulgently.

I'm just playing around with node.js and the express-module. I had an idea how to deal with browser-requests and now i have a simple question:

Is this a good idea/practice or is there a better solution to handle that?

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

http.createServer(app).listen(80);

app.get('/*',function(req,res,next){
    fs.exists(__dirname + req.url, function (exists) {
        if(exists)
        {
            console.log('Sending ' + __dirname + req.url + "...");
            res.sendfile(__dirname + req.url);      
        }
        else
        {
            console.log(__dirname + req.url + " not found!");
            res.send('Sorry, page not found.',404);     
        }
    });
});

Express is based on Connect and as such supports its middleware. And there is a perfect middleware for your situation: static file serving .

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

This will serve all files within the /public directory as static files available from the root directory. For routes which are not handled separately and for which no file exists, a 404 error is returned.

Btw. you want to put the listen -call to the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM