nodejs學習之表單提交(1)

nodejs做爲一門後端語言,接觸的最多的是它的框架,可是它自己的api我以爲更是非學不可,全部纔有了這篇文章html

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

HTML:json

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

知識點:api

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

2.fs讀取文件模塊框架

3.url模塊ide

4.解析url的querystring模塊post

有興趣的能夠參看api這裏就不一一細說了ui

相關文章
相關標籤/搜索