最近一段时间在学习前端向服务器发送数据和请求数据,下面总结了一下向服务器发送请求用get和post的几种不同请求方式:
1.用form表单的方法:
(1)get方法
前端代码:
<form action = "/login" method = "GET"> <label for = "username">账号:</label> <input type = "text" name ="username" placeholder = "请输入账号" required> <br> <label for = "password">密码:</label> <input type = "password" name = "password" placeholder = "请输入密码" required> <br> <input type = "submit" value = "登陆"></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方式。
以上这篇nodejs之get/post请求的几种方式小结就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。
新闻热点
疑难解答