var http = require('http');
var url = require('url');
createServer();
submitByGet();
submitByPost();
function createServer() {
http.createServer(function(req, res){
if(req.method.toUpperCase() == 'GET') {
res.writeHead(200, {'Content-Type': 'text/plain;charset=utf-8'});
res.write('submit by ' + req.method.toUpperCase() + '\n');
res.write(JSON.stringify(url.parse(req.url))+'\n');
res.end(url.parse(req.url).query+'\n');
} else if (req.method.toUpperCase() == 'POST') {
res.writeHead(200, {'Content-Type': 'text/plain;charset=utf-8'});
var postData = 'submit by ' + req.method.toUpperCase() + '\n';
req.addListener('data', function(data) {
postData += data;
}).addListener('end', function(data) {
res.write(postData+'\n');
res.end(JSON.stringify(url.parse(req.url))+'\n');
});
} else {
res.writeHead(404, {'Content-Type': 'text/plain;charset=utf-8'});
res.end("{'errcode':404,'errmsg':'404 网页未找到'}\n");
}
}).listen(8080, function(){
console.log('listen on port 8080...');
});
}
function submitByGet() {
var urlPath = 'http://127.0.0.1:8080/index.html?' + encodeURIComponent('name=龙神&password=123456');
http.get(urlPath, function(response){
response.setEncoding('utf-8');
console.log('状态码 : ' + response.statusCode);
console.log('response.headers = ' + JSON.stringify(response.headers));
var receivedData = '';
response.on('data', function(chunk) {
receivedData += chunk;
}).on('end', function() {
console.log('receivedRawData : ' + receivedData);
console.log('receivedDecodeData : ' + decodeURIComponent(receivedData));
});
}).on('error', function(e){
console.error(e.message);
});
}
function submitByPost() {
var sendData = {'name':'chy龙神', 'password':'123456'};
var postData = encodeURIComponent(JSON.stringify(sendData));
var req = http.request({port:'8080', path:'http://localhost:8080/index.html', method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, 'Content-Length': postData.length}, function(response){
response.setEncoding('UTF8');
console.log('状态码 : ' + response.statusCode);
console.log('response.headers = ' + JSON.stringify(response.headers));
var receivedData = '';
response.on('data', function(chunk) {
receivedData += chunk;
}).on('end', function(){
console.log('receivedRawData : ' + receivedData);
console.log('receivedDecodeData : ' + decodeURIComponent(receivedData));
});
}).on('error', function(e){
console.error(e.message);
});
req.write(postData);
req.end();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>get-post-demo</title>
</head>
<body>
<form method="get" action="http://127.0.0.1:8080" >
<input name="name" type="text" value="freddon" />
<input name="password" type="password" value="123456"/>
<input type="submit" value="submit by GET" />
</form>
<form method="post" action="http://127.0.0.1:8080" >
<input name="name" type="text" value="freddon" />
<input name="password" type="password" value="123456"/>
<input type="submit" value="submit by POST" />
</form>
</body>
</html>