nodejs之get/post請求的幾種方式

1.用form表單的方法:
(1)get方法
前端

前端代碼:jquery

<form action = "/login" method = "GET">web

 <label for = "username">帳號:</label>ajax

 <input type = "text" name ="username" placeholder = "請輸入帳號" required>express

 <br>npm

 <label for = "password">密碼:</label>json

 <input type = "password" name = "password" placeholder = "請輸入密碼" required>緩存

 <br>服務器

 <input type = "submit" value = "登錄">app

</form>

服務器代碼:

用get方法首先要配置json文件,在command中輸入命令npm-init ,而後要安裝所須要的express模塊,還須要在文件夾裏面建立一個放置靜態資源的文件夾(wwwroot),而後代碼以下:

var express = require('express');  //  引入模塊

var web = express();  // 使用模塊建立一個web應用

web.use(express.static('wwwroot'));  // 調用use方法 使用static方法

web.get('/login',function(request,response)  

{

    使用get方法 參數1 接口  參數2 回調函數 (參數1 向服務器發送的請求 參數2 服務器返回的數據)

    var name = request.query.username;    // 獲取前端發送過來的帳號

    var psw = request.query.password;      // 獲取前端發送過來的密碼

    response.status('200').send('輸入的內容是' + name + '<br>' + psw);

})

web.listen('8080',function()    // 監聽8080端口 啓動服務器

{

    console.log('服務器啓動中');

})

(2)post方法

前端:用post方法須要將form裏面的 method = GET 改爲 mthod = POST,表示使用post方法;

服務器:除get方法的要求外,還須要引入 body-parser模塊,以及對url進行編碼;

var express = require('express');
var bodyParser = require('body-parser');
var web = express();
web.use(express.static('wwwroot'));
// url 統一資源調配符 encoded 編碼 
web.use(bodyParser.urlencoded({extended:false}));
web.post('/login',function(request,response)
{
    var name = request.body.username;
    var psw = request.body.password;
    if(name != '599115316@qq.com' || psw != '123456')
    {
        response.send('<span style = "color:blue">登陸失敗</span>')
    }
    else
    {
        response.send('<span style = "color:red">登錄成功</span>')
    }
})
web.listen('8080',function()

{
    console.log('服務器啓動中');
})

2.xhr(XML HTTP Request方法 有三種請求方式 get/post/formdata)

XHR是ajax的核心,使用XHR能夠向服務器發送數據 也能夠解析服務器返回的數據;

(1)xhr之get方法:

前端:

<button click = "get()">get方法</button>

<script>

function()

{

    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function()

    {

        if(xhr.readyState == 4)

       {console.log(xhr.responseText)}   // 服務器接收到數據後返回的數據

    }

    xhr.open('/get','/comment?custom=小明&score=2&comment=商品質量通常,2分是給快遞小哥的');

    xhr.send();

// xhr.open(); 裏面有三個參數 ,參數1:設置xhr請求服務器的時候,請求的方式;參數2:設置請求的路徑和參數;(?是路徑和參數的分割線);參數3:設置同步請求仍是異步請求,不寫的話默認爲異步請求;

}

</script>

服務器:

首先也須要安裝所用到的模塊,而後請求模塊使用;

var express = require('expres');

var app = express();

app.use(express.static('wwwroot'));

app.get('/comment',function(request,response)

{

    response.send('已經接受到用get方法發來的評價');

})

app.listen('3000',function()

{

    console.log('服務器啓動中');

})

(2)xhr之post方法:

前端:

<button click = "post()">post方法</button>

<script>

function post()

{

    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function()

    {

         if(xhr.readyState == 4)

         {

              console.log('接收到服務器返回的信息' + xhr.responseText);

         }

    }

    xhr.open('post','/comment');  // post方法請求的參數不寫在open裏面,寫在send裏面,並且須要設置請求頭;

    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

    xhr.send('custom=小明&score=3&comment=商品還好,快遞也及時,可是就想給3分');

}

</script>

服務器:

須要引入post方法所用到的模塊(body-parser模塊)以及對url編碼;

var express = require('express');

var bodyParser = require('body-parser');

var app = express();

app.use(express.static('wwwroot'));

app.use(bodyParser.urlencoded({extended:false}));

app.post('/comment',function(request,response)

{

    response.send('已經接收到用post方法發送來的評價');

})

app.listen('3000',function()

{

    console.log('服務器啓動中');

})

(3)xhr之formdata方法:

前端:

<button click = "formdata()">formdata方法</button>

<script>

function formdata()

{

    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function()

   {

        if(xhr.readyState == 4)

        {

             console.log('formdata方法返回的數據是:' + xhr.responseText);

        }

   }

    xhr.open('post','/comment');

    var form = new FormData();

    form.append('custom','小明');

    form.append('score','5');

    form.append('comment','看你那麼辛苦,給你5分好了');

    xhr.send(form);

}

</script>

服務器:

var express = require('express');

var bodyParser = require('body-parser');

var multer = require('multer');   // 使用form表單所須要用到的一個模塊

var formData = multer();

var app = express();

app.use(express.static('wwwroot'));

app.use(bodyParser.urlencoded({extended:false}));

// 若是使用formdata提交的數據,必須在參數中使用array(),array()會先解析請求體當中的數據,再傳輸數據

app.post('/comment',formData.array(),function(request,response)  

{

    response.send('已經接收到用post方法發送來的評價');

})

app.listen('3000',function()

{

    console.log('服務器啓動中');

})

3.ajax請求:

通常狀況下都不須要使用ajax請求 使用ajax請求能夠獲取錯誤信息以及其它的一些指令,使用ajax須要引用jquery

(1)ajax之get:

前端:
<button id = "get">ajax-get</button>

<script>

$('#get').click(function()

{

    $.get('/login',{name:'小明',password:'123456'},function(data,status,xhr)

    {

         console.log('服務器返回的信息是' + data);

    })

// $.get() 發起一個get請求,參數1:請求的接口;參數2:傳遞給服務器的數據對象;參數3:回調函數(參數1:服務器返回的數據;參數2:狀態;參數3:xhr對象」);

})

</script>

服務器:

var express = require('express');

var app = express();

app.use(express.static('wwwroot'));

app.get('/login',function()

{

    if(request.query.name == '小明' && request.query.password == '123456')

    {

         response.send('登陸成功');

    }

    else

    {

         response.send('登陸失敗');

    }

})

app.listen('8080',function()

{

    console.log('服務器啓動中');

})

(2)ajax之post:

前端:

<button id = 'post'>ajax-post</button>

<script>

    $('#post').click(function()

{

    $.post('/login',{name:'小明',password:'666'},function(data,status,xhr)

    {

          console.log('服務器返回的數據:' + data)

    })

})

</script>

服務器:

var express = require('express');

 

var bodyParser = require('body-parser');

 

 

var app = express();

 

app.use(express.static('wwwroot'));

 

app.use(bodyParser.urlencoded({extended:false}));

app.listen('8080',function()

{

    console.log('服務器啓動中');

})

app.post('/login',function(request,response)

{

    if(request.body.name == '小明' && request.body.password == 666)

   {

        response.send('登陸成功');

   }

    else

    {

         response.send('登陸失敗');

    }

})

(2)ajax之ajax:

前端:

<button id ="ajax">ajax請求</button>

<script>

    $('#id').click(function()

{

// $.ajax() 發起ajax請求;

    $.ajax({

     url :'/login',                // 請求的接口地址

     type:'post',                 // 請求的方式,默認爲get請求

     data:{name:'小明',password:'123'},   // 發送到服務器的數據

     timeout:10000,              // 超時  (10s)

     cache:true,                     // 緩存 默認爲true

     async:true,                     // 是否異步 

// 同步任務(sync) :當上一個任務沒有完成的時候,下一個任務沒法開啓,有可能會卡死主線程;

//異步任務(Async):當上一個任務沒有完成的時候,下一個任務仍然會被執行,用戶體驗性好;

     success:function(data,status,xhr)

    {

         console.log('服務器返回的數據是:' + data);

         console.log('返回的信息是:' + xhr.getAllResponseHeaders());

    }

    error:function(xhr,status,error)

    {

        console.debug('錯誤信息:' + error);

    }

    complete:function(xhr,status)

    {

          console.log('所有流程結束');

    }

})                   

})

</script>

服務器裏面可使用上面ajax的get和post方法的代碼,ajax請求的方式經過type設置爲get方式仍是post方式。

相關文章
相關標籤/搜索