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);
	}
}

猜你喜欢

转载自blog.csdn.net/u013101178/article/details/84576577