1. 程式人生 > >Nodejs:動態網頁

Nodejs:動態網頁

login.html

<html>

<head>
	<meta charset="UTF-8">
</head>

<body>
	登入頁面
	<img src="./showimg" /><br/>

	收到引數:email是{email}<br/>
    密碼是:{pwd}

	<form action="./login" method="post">
		<table align="center">
			<tr>
				<td>email:</td>
				<td><input type="text" name="email" /></td>
			</tr>
			<tr>
				<td>pwd:</td>
				<td><input type="text" name="pwd" /></td>
			</tr>

			<tr>
				<td align="center">
					<input type="submit" value="提交">
				</td>
			</tr>
		</table>
	</form>
</body>

</html>

router.js

var optfile = require('../model/optfile2.js');
var url = require('url');//url需匯入
var querystring = require('querystring'); //post需匯入

function getRecall(req, res) {
	res.writeHead(200, {
		'Content-Type': 'text/html;  charset=utf-8'
	});

	function recall(data) {
		res.write(data);
		res.end(''); //不寫則沒有http協議尾
	}
	return recall;
}

module.exports = {
	login: function (req, res) {

		//-------post方式接收引數----------------2      
		var post = ''; //定義了一個post變數,用於暫存請求體的資訊      
		req.on('data', function (chunk) { //通過req的data事件監聽函式,每當接受到請求體的資料,就累加到post變數中      
			post += chunk;
		});
		//-------注意非同步-------------      
		req.on('end', function () { //在end事件觸發後,通過querystring.parse將post解析為真正的POST請求格式,然後向客戶端返回。      
			post = querystring.parse(post);
			if (post['email'] != undefined && post['pwd'] != undefined) {
				console.log('email:' + post['email'] + '\n');
				console.log('pwd:' + post['pwd'] + '\n');
			}
			//重寫recall
			function recall(data) {
				arr = ['email', 'pwd']
				dataStr = data.toString();
				for (var i = 0; i < arr.length; i++) {
					re = new RegExp('{' + arr[i] + '}', 'g');///\{name\}/g
					dataStr = dataStr.replace(re, post[arr[i]]);
				}
				res.write(dataStr);
				res.end(''); //不寫則沒有http協議尾
			}
			//recall = getRecall(req, res);
			optfile.readfile('./view/login.html', recall);
		});
	},
	showimg: function (req, res) {
		res.writeHead(200, {
			'Content-Type': 'image/jpeg'
		});
		optfile.readImg("./view/pig.png", res);
	}
}