参考: http://www.tutorialspoint.com/nodejs/nodejs_express_framework.htm
■ ハローワールド
ファイル:app.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
// app.get('/index.htm', function (req, res) {
// res.sendFile( __dirname + "/" + "index.htm" );
// })
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
■ GETメソッド
ファイル:index.htm
項目入力を作成
フォームの送信先を action="http://127.0.0.1:3000/process_get" にする
ファイル:app.js
public ファイルの公開(ブラウザで直接URLを指定して表示できるファイル)
index.htm の表示
process_get の表示(応答)
サーバーの listen
■ POSTメソッド
ファイル:index.htm
項目入力を作成
フォームの送信先を action="http://127.0.0.1:3000/process_post" にする
ファイル:app.js
urlencodedParser の用意
public ファイルの公開(ブラウザで直接URLを指定して表示できるファイル)
index.htm の表示
process_post の表示(応答)
サーバーの listen
■ ファイルアップロード
ファイル:index.htm
ファイル名を選択(input type="file")
フォームの送信先を action="http://127.0.0.1:3000/file_upload" にする
また、enctype="multipart/form-data" で、POST
ファイル:app.js
bodyParser の用意
multer の用意(ファイルアップロードのモジュール)
public ファイルの公開(ブラウザで直接URLを指定して表示できるファイル)
index.htm の表示
file_upload の応答(POST)
保存先のファイル名を用意
readFile( path, function () { writeFile( file, data, function () {
結果表示
});
});
サーバーの listen
■ クッキー
ファイル:app.js
cookieParser の用意
/ の表示時に、req.cookies で、クライアントから送られたクッキーを取得
サーバーの listen
■ MySQL
参考:https://codeforgeek.com/2015/01/nodejs-mysql-tutorial/
参考:http://atmarkplant.com/nodejs-mysql-basic/
package.json - "dependencies": { - "mysql": "^2.5.4"
npm install
ファイル:app.js
var express = require("express");
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'mysql001.db.com',
user : 'laa0397',
password : 'abcdef',
database : 'laa0397-db'
});
var app = express();
connection.connect(function(err){
if (!err) {
console.log("Database is connected ... nn");
} else {
console.log("Error connecting database ... nn");
}
});
app.get("/control/mysql_responds", function(req,res) {
connection.query('SELECT * from co_person', function(err, rows, fields) {
connection.end();
if (!err)
console.log('The solution is: ', rows);
else
console.log('Error while performing Query.');
});
});
app.listen(3000);
→ 更にプール接続に変更する
■ HTTPS
ファイル:bin/www
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('/var/www/html/homepage/keys/server.rsa'),
cert: fs.readFileSync('/var/www/html/homepage/keys/server.crt')
};
var server = https.createServer(options, app);
■ ルーティング / ビュー / パブリック
ファイル&フォルダ:
routes / index.js、users.js
views / index.ejs
public
render を実行すると、ビューに置かれ編集した HTML を表示する
send を実行すると、データを送信する
■ ボタン押下
ファイル:views / index.ejs
<input name="like" id="like" value="Like" type="submit" /> <input name="count" id="count" value="0" type="text" readonly />
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$('#like').click(function(){
$.post(
'/test',
{name:"ABC", email:"abc@yahoo.com"},
function(data){
$('#count').val(data);
}
)
});
</script>
ファイル:routes / index.js
/* Button click. */
var count = 0;
router.post('/test', function (req, res) {
count += 1;
res.send(String(count));
console.log('works');
});
■ 空きメモリ量
ファイル:views / index.ejs
空きメモリ量<span id="freemem"></span><br>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
setInterval(function() {
$.get(
'/freemem',
function(data){
$('#freemem').text(String((Number(data)/1024/1024/1024).toFixed(3))+' GB');
}
)
}, 300);
</script>
ファイル:routes / index.js
/* Memory information. */
const os = require('os');
router.get('/freemem', function (req, res) {
res.send(String(os.freemem()));
console.log('freemem');
});
■ HTTP プロキシ(HTTPS プロキシ)
ファイル:proxy.js
var http = require('http');
var httpProxy = require('http-proxy');
var url = require('url');
var proxy = httpProxy.createProxyServer({});
var server = http.createServer(function(req, res) {
if (req.headers == null || req.headers.host == null || req.url == null) {
// do nothing
}
else {
var hostname = req.headers.host.split(":")[0];
var pathname = url.parse(req.url).pathname;
if (hostname == 'example.com' || hostname == 'apache.example.com') {
proxy.web(req, res, { target: 'https://localhost:8443', secure: false });
} else if (hostname == 'node.example.com') {
proxy.web(req, res, { target: 'https://localhost:8124', secure: false });
} else {
res.writeHead(404);
res.end();
}
}
});
server.listen(80);
(作成中)