最近一段时间在学习前端向服务器发送数据和请求数据,下面总结了一下向服务器发送请求用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>
新闻热点
疑难解答
图片精选