nodejs之get/post请求的几种方式小结

2020-06-17 06:45:45易采站长站整理

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方法:

前端: