0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.js / express / APIサーバ開発環境構築 ~ HTTPリクエストを受けるまで~

Last updated at Posted at 2020-02-01

はじめに

気軽にNodeでプロジェクトを作成したい時用。
GETでJSONを返すところまで。

最終フォルダ構成は以下の様になる。

node-app
├── node_modules
├── index.js
├── package-lock.json
├── package.json
├── router.js
└── .gitignore

Set up Node project

package.json作成

$ npm init -y

-yで対話での設定をスルーして、デフォルト設定となる。ちゃんと設定する場合は、-yは外す。

最低限必要なライブラリのインストール

$ npm install --save express morgan body-parser
  • express: Webフレームワーク
  • morgan: ロギング
  • body-parser: HTTPのリクエストボディを変換

現状のpackage.json

package.json
{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "mongoose": "^5.8.11",
    "morgan": "^1.9.1"
  }
}

Git管理不要なリソースの設定

トップ階層に.gitignoreファイルを作って以下を書いておく

node_modules/

実装

トップ階層にindex.jsを作成。アプリケーションのスタート地点になる。

index.js
// Libraries Setup
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const app = express();

// App Setup
app.use(morgan('combined'));
app.use(bodyParser.json({ type: '*/*' }))

// Server Setup
const port = process.env.PORT || 3090;  // 任意のポート番号でOK
const server = http.createServer(app);
server.listen(port);
console.log('Server listening on:', port);

プログラムの起動

$ node index.js

(Option)nodemonの設定

nodemonを使うと、実装時の変更をキャッチして、アプリケーションを再起動してくれる。

$ npm install --save-dev nodemon
$ nodemon index.js  //起動

以下の様にpackage.jsonのscriptsに設定しておいても良い。

package.json
...
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev" : "nodemon index.js"
  },
...

以下で起動できるようになる。

$ npm run dev

起動結果

ブラウザからlocalhost:3090にアクセス。
スクリーンショット 2020-02-01 18.03.32.png

--

$ npm run dev

> server@1.0.0 dev /Users/mozuku/Documents/server
> nodemon index.js

[nodemon] 2.0.2
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
Server listening on: 3090
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
::1 - - [01/Feb/2020:09:01:14 +0000] "GET / HTTP/1.1" 404 139 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36"

サーバを起動した状態でファイルを編集するとnodemonが変更を検知して、再起動してくれる。またmorganのおかげで、上記の最終行にHTTPのログが残っている。現在、ルーティングの設定をしていないので、404が返っているのがわかる。

HTTPリクエストを受けられる様にRouteの設定

トップ階層にroute.jsを作って、index.jsでインポートする。
パス"/"に対するGETリクエストに対して、テキトーなJSONを返す。

route.js
module.exports = function(app) {
    app.get('/', function(req, res, next) {
        res.send(['apple', 'orange', 'strawberry']);
    });
}
index.js
// Libraries Setup
...
const morgan = require('morgan');
const app = express();
const router = require('./router'); // 追加!!!

// App Setup
app.use(morgan('combined'));
app.use(bodyParser.json({ type: '*/*' }))
router(app);  // 追加!!!
...

ブラウザで確認

スクリーンショット 2020-02-01 18.14.15.png

JSONが返ってきているのが確認できる。

おわりに

Nodeプロジェクトの開発を始めれるところぐらいまでをメモ。気軽にプロジェクトを始める際の土台になればと思う。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?