LoginSignup
10
10

More than 5 years have passed since last update.

expressのよくある設定メモ

Posted at

express使ってモックを作ったりするときの、よくある設定のメモです。

Jadeのprettyを有効にする

古いバージョンのexpressとやり方違うので注意。基本開発環境のみの設定なので、環境がdevelopmentのときだけ適用。

app.js
if ('development' === app.get('env')) {
  app.locals.pretty = true;
}

livereload

connect-livereloadを使ったやり方。こちらも開発環境のみ適用。

app.js
if ('development' === app.get('env')) {

  var liveReloadPort = 35729,
      excludeList = ['.css', '.html','.js'];

  app.use(require('connect-livereload')({  
    port: liveReloadPort,
    excludeList: excludeList
  }));
}

virtual hosting

第2引数がexpress()。

app.js
app.use(express.vhost('www.example.com',require('./path/to/express/app.js')));

requireする場合は、読み込まれる側でexportしておく。

app.js
var app = module.exports = express();

アップロードファイルのTEMPディレクトリ設定

connect.multipartの設定。

app.js
app.use(express.bodyParser({
  uploadDir : './files/'
}));

セッション使う

セッショーン。

app.js
app.use(express.session());

ベーシック認証

ベーシックな認証。

app.js
app.use(express.basicAuth(function(user,pass){
  return username === user && password === pass;
},'some message'));

socket.io

soket.ioとは関係ないけど、本番時には立ち上げ後にユーザ変更する。

app.js
var server = http.createServer(app),
    io = require('socket.io').listen(server);

server.listen(app.get('port'), function(){

  if ('development' !== app.get('env')) {
    process.setuid('www-data');
  }

  console.log('Express server listening on port ' + app.get('port'));
});

おしまい。

10
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10