一个简单的web服务器
用于接收前台传过来的表单数据。node中的Content-Type为unlencoded。表单和url的参数是经过编码的。
var http = require('http');
var qs = require('querystring');
http.createServer(function(req,res){
console.log(req.url);
if(req.url == '/'){
res.writeHead(200,{'Content-Type':'text/html'});
res.end(['<form method="POST" action="/url">'
,'<h1>My form</h1>'
,'<fieldset>'
,'<label>Personal information</label>'
,'<p>What is your name?</p>'
,'<input type="text" name="name">'
,'<p><button>submit</button></p>'
,'</form>'].join(''));
}else if(req.url == '/url'&& 'POST' == req.method){
var body = '';
req.on('data',function (chunk) {
body+=chunk;
})
req.on('end',function () {
res.writeHead(200,{'Content-Type':'text/html'});
res.end('<p>Content-Type:'+req.headers['content-type']+'</p>'+'<p>data:'+qs.parse(body).name+'</p>');
})
}else{
res.writeHead(400);
res.end('404 NOT FOUND');
}
}).listen(3000);
node提供了一个称为querystring的模块,可以解析这类字符串。例如上文中的qs.parse(body)。
为了排除其他url,可以使用一个else 加入404处理。
发送请求可以使用request模块
require('http').request({
host:'127.0.0.1',
port:3000,
url:'/',
method:'GET'
},function(res){
var body = '';
res.setEncoding('utf8');
req.on('data',function (chunk) {
body+=chunk;
})
req.on('end',function () {
console.log('data:'+body);
})
})