express 功能

————————————————————–
比 ejs 更好的套件
var engine = require(‘ejs-locals’);
router.engine(‘ejs’, engine);
router.set(‘views’, ‘./views’);
router.set(‘view engine’, ‘ejs’);
————————————————————–

設定的寫法
app.configure(function() {
app.set(“views”, __dirname + “/views”);
app.set(“view engine”, “jade”);
});
————————————————————–

app = express.createServer(express.logger()),
io = require(“socket.io”).listen(app);

io.sockets.on(“connection”, function (socket) {
socket.emit(“front-end”, { hello: “world” });
socket.on(“my other event”, function (data) {
console.log(data);
});
});

app.get(/(.*)\.(jpg|gif|png|ico|css|js|txt)/i, function(req, res) {
res.sendfile(__dirname + “/” + req.params[0] + “.” + req.params[1], function(err) {
if (err) res.send(404);
});
});

基本 http auth 認證

app.use((req, res, next) => {

// authentication middleware
const auth = {login: ‘test’, password: ‘123’} // change this

// parse login and password from headers
const b64auth = (req.headers.authorization || ”).split(‘ ‘)[1] || ”
const [login, password] = Buffer.from(b64auth, ‘base64’).toString().split(‘:’)

// Verify login and password are set and correct
if (login && password && login === auth.login && password === auth.password) {
// Access granted…
return next()
}

// Access denied…
res.set(‘WWW-Authenticate’, ‘Basic realm=”401″‘) // change this
res.status(401).send(‘Authentication required.’) // custom message

})