最近一段时间在学习前端向服务器发送数据和请求数据,下面总结了一下向服务器发送请求用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请求的几种方式的更多相关文章

  1. 第二节:SSL证书的申请、配置(IIS通用)及跳转Https请求的两种方式

    一. 相关概念介绍 1. SSL证书服务 SSL证书服务由"服务商"联合多家国内外数字证书管理和颁发的权威机构.在xx云平台上直接提供的服务器数字证书.您可以在阿里云.腾讯云等平台 ...

  2. C#中Post请求的两种方式发送参数链和Body的

    POST请求 有两种方式 一种是组装key=value这种参数对的方式 一种是直接把一个字符串发送过去 作为body的方式 我们在postman中可以看到 sfdsafd sdfsdfds publi ...

  3. Spring MVC中forward请求转发2种方式(带参数)

    Spring MVC中forward请求转发2种方式(带参数) http://www.51gjie.com/javaweb/956.html  

  4. 解决 SharePoint 2010 拒绝访问爬网内容源错误的小技巧(禁用环回请求的两种方式)

    这里有一条解决在SharePoint 2010搜索爬网时遇到的“拒绝访问错误”的小技巧. 首先要检查默认内容访问帐户是否具有相应的访问权限,或者添加一条相应的爬网规则.如果目标资源库是一个ShareP ...

  5. nginx分发请求的2种方式:1、指明server_name;2、通过location过滤uri来分发请求;

    user nginx; worker_processes 8; # = cpu num; error_log /data/nginx/log/error/error.log warn; # warn, ...

  6. JavaScript处理异步请求的几种方式(取异步函数返回值)

    JavaScript处理异步的几种方式 Javascript语言的执行环境是"单线程"(single thread,就是指一次只能完成一件任务.如果有多个任务,就必须排队,前面一个 ...

  7. WebAPI GET和POST请求的几种方式

    GET请求 1.无参数get请求 一般get请求有两种写法,一种是$.get()   一种是$.ajax({type:"get"}),我个人比较喜欢用后者. 下面例子主要是get无 ...

  8. springmvc 前端 发ajax请求的几种方式

    一.传json单值或对象 1.前端 var data = {'id':id,'name':name}; $.ajax({ type:"POST", url:"user/s ...

  9. java发送http get请求的两种方式

    长话短说,废话不说 一.第一种方式,通过HttpClient方式,代码如下: public static String httpGet(String url, String charset) thro ...

随机推荐

  1. webp图片实践之路

    最近,我们在项目中实践了webp图片,并且抽离出了工具模块,整合到了项目的基础模板中.传闻IOS10也将要支持webp,那么使用webp带来的性能提升将更加明显.估计在不久的将来,webp会成为标配. ...

  2. 浅谈WEB页面提速(前端向)

    记得面试现在这份工作的时候,一位领导语重心长地谈道——当今的世界是互联网的世界,IT企业之间的竞争是很激烈的,如果一个网页的加载和显示速度,相比别人的站点页面有那么0.1秒的提升,那也是很大的一个成就 ...

  3. 异常处理汇总 ~ 修正果带着你的Net飞奔吧!

    经验库开源地址:https://github.com/dunitian/LoTDotNet 异常处理汇总-服 务 器 http://www.cnblogs.com/dunitian/p/4522983 ...

  4. echarts+php+mysql 绘图实例

    最近在学习php+mysql,因为之前画图表都是直接在echart的实例demo中修改数据,便想着两相结合练习一下,通过ajax调用后台数据画图表. 我使用的是echart3,相比较第二版,echar ...

  5. 【NLP】Python NLTK处理原始文本

    Python NLTK 处理原始文本 作者:白宁超 2016年11月8日22:45:44 摘要:NLTK是由宾夕法尼亚大学计算机和信息科学使用python语言实现的一种自然语言工具包,其收集的大量公开 ...

  6. [原] KVM 虚拟化原理探究(5)— 网络IO虚拟化

    KVM 虚拟化原理探究(5)- 网络IO虚拟化 标签(空格分隔): KVM IO 虚拟化简介 前面的文章介绍了KVM的启动过程,CPU虚拟化,内存虚拟化原理.作为一个完整的风诺依曼计算机系统,必然有输 ...

  7. RMS去除在线认证

    在微软 OS 平台创建打开 RMS 文档如何避免时延 相信我们在企业内部的环境中已经部署了微软最新的OS平台,Windows 7和Windows 2008 R2,在这些OS平台上使用IRM功能时,您有 ...

  8. Java 进阶 hello world! - 中级程序员之路

    Java 进阶 hello world! - 中级程序员之路 Java是一种跨平台的语言,号称:"一次编写,到处运行",在世界编程语言排行榜中稳居第二名(TIOBE index). ...

  9. MongoDB学习笔记二—Shell操作

    数据类型 MongoDB在保留JSON基本键/值对特性的基础上,添加了其他一些数据类型. null null用于表示空值或者不存在的字段:{“x”:null} 布尔型 布尔类型有两个值true和fal ...

  10. python之浅拷贝和深拷贝

    1.浅拷贝 1>赋值:从下面的例子我们可以看到赋值之后新变量的内存地址并没有发生任何变化,实际上python中的赋值操作不会开辟新的内存空间,它只是复制了新对象的引用,也就是说除了b这个名字以外 ...