LoginSignup
65
58

More than 5 years have passed since last update.

Node.jsとExpressとMySQLの簡単サンプル

Last updated at Posted at 2017-09-24

はじめに

今までnodeと言えば、npmでフロントで使うもろもろをinstallするためのJS実行環境くらいのイメージでしたが、webサーバーも作れるということなので作ってみました。

スペック

  • フロントエンドエンジニア
  • node,npmはフロントエンド関連での利用あり
  • インフラやサーバーの知識は少々
  • MySQLの知識も少々

Node.jsのみ

nodeが動く環境なら確認ができる。

ソースコード

置き場

index.js

var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(1234);

結果

node index.jsで実行し、localhost:1234にアクセス。

やってることは文字列を返しているだけですが、これだけでwebサーバーとして動くのにかなりびっくりです。

スクリーンショット 2017-09-24 16.19.51.png

Express

node.jsでwebサーバーを作ることが確認できました。

つまり、webサーバーを簡単に作るフレームワークがたくさんあるということです。

Expressはそんなフレームワークの1つです。

公式サイト

インストール

npm install express --save

ソースコード

置き場

index.js

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

結果

node index.jsで実行し、localhost:3000にアクセス。

これも文字列を返してるだけですが、簡単に作れました。

さすがフレームワーク。知らなくても、なんとなくソースコードが読める。

スクリーンショット 2017-09-24 16.24.33.png

MySQL

webサーバーということはDBからデータを取って表示したいですよね?

そう、node.jsならそれができます。

npm経由でmysqlをinstallすればJSからMySQLの操作ができます。

※個人的にはJSでMySQLを操作なんて驚き

インストール

npm install mysql --save

データの作成

全てmysqlログイン後

create database NodeTest;

use NodeTest;

create table test_table(id int(11),name varchar(255));

insert into test_table values(1,'testname');

ソースコード

置き場

index.js

var express = require('express');
var app = express();

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'root',
  database : 'NodeTest'
});

app.get('/', function (req, res) {
  connection.query('select * from test_table', function (error, results, fields) {
    if (error) throw error;
    res.send(results[0]);
  });
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

結果

node index.jsで実行し、localhost:3000にアクセス。

無事MySQLからデータを取得し表示できました。

スクリーンショット 2017-09-24 16.15.57.png

所感

簡単にwebサーバーが作れて、しかもMySQLから簡単にデータを取得できてました。

簡単な個人用のサービスとかならこれで作れる幅が一気に増えそう。

今回はただの文字列を返しましたが、次回はHTMLを返すようにしてみます。

65
58
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
65
58