アプリ作成手順
Expressでアプリを作成するには、以下4つの手順があります。
1. アプリケーションのフォルダーを作成する。
2. コマンドを使い、npmの初期化をする。
3. expressをアプリケーションにインストールする。
4. プログラムのファイルを作成してソースコードを書く。
1. アプリケーションのフォルダーを作成する。
$ mkdir express-app
$ cd express-app
2. コマンドを使い、npmの初期化をする。
コマンドを実行し、npmの初期化をします。基本すべてEnterを押してデフォルトのままで大丈夫です。
一応下記に項目の内容を記載します。
項目 | 説明 |
---|---|
version | バージョン番号 |
description | プロジェクトの説明文 |
entry point | 起動用のスクリプトファイル名 |
test command | テスト実行のコマンド |
git repository | 利用するGitリポジトリ |
keywords | 関連するキーワード |
author | 作者名 |
license | ライセンスの種類 |
$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help init` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (express-app)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
{
"name": "express-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes) yes
3. expressをアプリケーションにインストールする。
下記コマンドを実行すれば、expressをインストールすることができます。
$ npm install --save express
4. プログラムのファイルを作成してソースコードを書く。
プログラムのファイルを作成していきます。起動用のスクリプトファイル名をindex.jsに設定したため、index.jsを作成し、コードを記載していきます。
$ touch index.js
index.js
// expressオブジェクトの作成
const express = require('express')
// Expressのアプリケーション本体となるオブジェクトの作成
const app = express()
// ルーティングの設定
app.get('/', (req, res) => {
res.send('Welcome to Express!')
})
// 待ち受けの開始
app.listen(3000, () => {
console.log('Start server port:3000')
})
あとはプログラムを実行して、結果を確認していきます。
コンソールにはconsole.logにて記載した部分が出力されます。
$ node index.js
Start server port:3000
また、http://localhost:3000/ にアクセスするとres.sendにて記載した部分がクライアントに表示されます。