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

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

$
0
0

はじめに

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

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

sample-node-app/
- node_modules
- index.js
- package.json
- package-lock.json
- router.js
- .gitignore

Nodeプロジェクトセットアップ

package.json作成

$npm init

色々質問されるがめんどくさければ、全てEnterで飛ばしてOK!

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

$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 Setupconstexpress=require('express');consthttp=require('http');constbodyParser=require('body-parser');constmorgan=require('morgan');constapp=express();// App Setupapp.use(morgan('combined'));app.use(bodyParser.json({type:'*/*'}))// Server Setupconstport=process.env.PORT||3090;// 任意のポート番号でOKconstserver=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

--

mozuku:server mozuku$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...constmorgan=require('morgan');constapp=express();constrouter=require('./router'); // 追加!!!// App Setupapp.use(morgan('combined'));app.use(bodyParser.json({type:'*/*'}))router(app);// 追加!!!...

ブラウザで確認

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

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

おわりに

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


Viewing all articles
Browse latest Browse all 9027

Trending Articles