Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9155

Node.js(Express)のアプリ作成手順

$
0
0

アプリ作成手順

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オブジェクトの作成constexpress=require('express')// Expressのアプリケーション本体となるオブジェクトの作成constapp=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にて記載した部分がクライアントに表示されます。
image.png


Viewing all articles
Browse latest Browse all 9155

Trending Articles