nodejs學習之表單提交(1)


nodejs作為一門后端語言,接觸的最多的是它的框架,但是它本身的api我覺得更是非學不可,所有才有了這篇文章

表單提交是最基本的也是最實用的入門實例

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>main</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div id="div1" style="width: 350px;">
    <form id="form1" method="post" action="postlogin" >
        <fieldset>
            <legend>表單1</legend>
            姓名:<input type="text" name="username" /><br />
            學歷:<select name="education">
            <option value="中學">中學</option>
            <option value="大專">大專</option>
            <option value="本科">本科</option>
            <option value="碩士">碩士</option>
            <option value="博士">博士</option>
        </select><br />
            住址:<input type="text" name="address" />
            隱藏:<input name="hide" disabled="disabled" value="111" />
            <input type="submit" value="提交" />
        </fieldset>
    </form>
</div>
</body>
</html>

server端:

var httpserver = require("http");
var qs = require("querystring");
var url = require("url");
var fs = require("fs");

httpserver.createServer(onRequest).listen(3000);

function onRequest(request,response)
{
    var pathname = url.parse(request.url).pathname;
    if(pathname=="/")    //訪問表單頁面
    {
        response.writeHead(200,{"Content-Type":"text/html"});
        fs.readFile("index.html","utf-8",function(e,data){
            response.write(data);
            response.end();
        });
    }
    else if(pathname=="/postlogin")    //處理post方式請求
    {
        var urlstr="";
        request.addListener("data",function(postdata){
            urlstr+=postdata;    //接收到的表單數據字符串,這里可以用兩種方法將UTF-8編碼轉換為中文
            var jsondata = qs.parse(urlstr);        //轉換成json對象
            var decodedata = decodeURIComponent(urlstr);        //對表單數據進行解碼
            console.log(urlstr);
            console.log(jsondata);
            console.log(decodedata);
            urlstr = decodedata;
        });
        request.addListener("end",function(){
            response.writeHead(200,{"Content-Type":"text/plain; charset=utf-8"});
            response.write(urlstr);
            response.end();
        });
    }
    else if(pathname=="/getlogin")    //處理get方式請求
    {
        var urlstr = url.parse(request.url).query;
        var jsondata = qs.parse(urlstr);
        var decodedata = decodeURIComponent(urlstr);

        console.log(urlstr);
        console.log(jsondata);
        console.log(decodedata);
        urlstr = decodedata;

        response.writeHead(200,{"Content-Type":"text/plain; charset=utf-8"});
        response.write(urlstr);
        response.end();
    }
    else
    {
        response.writeHead(200,{"Content-Type":"text/plain"});
        response.write("error");
        response.end();
    }
}

知識點:

1.node創建一個簡單的服務器

2.fs讀取文件模塊

3.url模塊

4.解析url的querystring模塊

有興趣的可以參看api這里就不一一細說了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM