总结下常见的几种js请求方式
先准备好服务端代码,这里用express框架来构建服务端:
const express = require("express"); var bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.all('*', function (req, res, next) { //设为指定的域 res.header('Access-Control-Allow-Origin', "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header('Access-Control-Allow-Headers', 'Content-Type'); res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS"); res.header('Access-Control-Allow-Credentials', true); res.header("X-Powered-By", ' 3.2.1'); next(); }); app.get("/data", (req, res) => { res.send("hello world"); }); app.get("/data/1", (req, res) => { res.send("hello world1"); }); app.get("/data/2", (req, res) => { res.send("hello world2"); }); app.get("/data/3", (req, res) => { res.send("hello world3"); }); app.get('/data/books', (req, res) => { res.send(req.query); }); app.post('/data/comment', (req, res) => { console.log(req.body); res.send(req.body); }); app.listen(3000, function () { console.log('the server is running...'); });
普通的ajax请求,即通过XMLHTTPRequest对象来发送请求:
<script> var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if (xhr.readyState === 4) { console.log(xhr.responseText); } }; xhr.open("get", "http://localhost:3000/data"); xhr.send(null); </script>
通过jquery的ajax方法来发送请求:
<script> $.ajax({ url: "http://localhost:3000/data", type: "get", success: function(data){ console.log(data); } }); </script>
上面的两种方法虽然能发送异步请求得到相应结果,如果发送多个异步请求则无法保证得到的响应的顺序,因此只能不断的嵌套,如:
<script> $.ajax({ url: "http://localhost:3000/data/1", type: "get", success: function(data){ console.log(data); $.ajax({ url: "http://localhost:3000/data/2", type: "get", success: function(data){ console.log(data); } }); } }); </script>
为了解决这种情况,可以使用Promise语法。
使用Promise来处理回调:
<script> function ajax(url){ return new Promise(function (resolve, reject) { $.ajax({ url: url, type: "get", success: function(data){ resolve(data); }, error: function(error) { reject(error); } }); }); } ajax("http://localhost:3000/data/1").then(function(data){ console.log(data); return ajax("http://localhost:3000/data/2"); }).then(function (data) { console.log(data); return ajax("http://localhost:3000/data/34"); }).then(function(data){ console.log(data); }).catch(function(err){ console.log('err'); }).finally(function(){ console.log('我一定会执行'); }); </script>
上面首先定义了一个函数ajax,其参数为要请求的url,这个函数返回一个Promise对象,在Promise对象中处理异步请求,如果请求成功,则调用resolve方法,否则调用reject方法。之后就可以调用该函数,该函数返回的Promise对象可以调用then方法,该方法可以传入一个函数,对应着Promise的resolve,其形参data即请求得到的数据。之后如果想要继续发送异步请求,则可以返回ajax函数,即返回一个新的Promise对象,之后就可以继续用then来获取数据。通过这种方法可以链式编程,从而避免代码的嵌套问题。代码中的catch函数可以捕获Promise中的错误,而finally函数则必定会执行。
Promise还有两个方法,一个是Promise.all(),另一个是Promise.race():
<script> function ajax(url){ return new Promise(function (resolve, reject) { $.ajax({ url: url, type: "get", success: function(data){ resolve(data); }, error: function(error) { reject(error); } }); }); } var p1 = ajax("http://localhost:3000/data/1"); var p2 = ajax("http://localhost:3000/data/2"); var p3 = ajax("http://localhost:3000/data/3"); Promise.all([p1,p2,p3]).then(function(result){ console.log(result); }); Promise.race([p1,p2,p3]).then(function(data){ console.log(data); }); </script>
Promise.all()接受一个数组,数组中存储着Promise对象,数组中的Promise对象都会执行then。then()的形参result是一个数组,分别是三个Promise的响应。而Promise.race()也是接受一个数组,但是只会执行其中一个Promise对象,故then()的形参data就是响应最快的那个Promise的响应。
使用fetch API来发送请求。
(1)发送GET请求
<script> fetch("http://localhost:3000/data",{
method: "get"
}).then((data) => { return data.text(); }).then((data)=>{ console.log(data); }) </script> </body>
fetch()有两个参数,第一个是请求的url,第二个是配置选项。默认是发送GET请求
(2)发送POST请求
<script> fetch("http://localhost:3000/data/comment",{ method: "post", body: JSON.stringify({ id: 1, name: "《Javascript》" }), headers: { "Content-Type": "application/x-www-form-urlencoded" } }).then(function(data){ return data.text(); }).then(function(data){ console.log(data); }); </script>
在第二个参数中指定类型为POST请求,并在body中写入参数。
使用axios来发送请求
(1)发送GET请求
<script> axios.get("http://localhost:3000/data?id=1").then(function(ret){ console.log(ret.data); }); axios.get("http://localhost:3000/data/books",{ params: { id: 1, name: "Vue.js" } }).then(function(ret){ console.log(ret.data); }); </script>
第一种是在urL里面添加参数,第二种是在params对象中以键值对的形式添加参数。
(2)发送POST请求
<script> axios.post("http://localhost:3000/data/comment", { id: 1, name: "nodejs" }).then((ret) => { console.log(ret.data); }) </script>