先准備好服務端代碼,這里用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>
