接口調用方式
- 原生ajax
- 基於jQuery的ajax
- fetch
- axios
這裏主要講一下fetch和axios
fetch
- Fetch API是新的ajax解決方案 Fetch會返回Promise
- fetch不是ajax的進一步封裝,而是原生js,沒有使用XMLHttpRequest對象。
- fetch(url, options).then()
<script type="text/javascript">
/*
Fetch API 基本用法
fetch(url).then()
第一個參數請求的路徑 Fetch會返回Promise 所以我們可以使用then 拿到請求成功的結果
*/
fetch('http://localhost:3000/fdata').then(function(data){
// text()方法屬於fetchAPI的一部分,它返回一個Promise實例對象,用於獲取後臺返回的數據
return data.text();
}).then(function(data){
// 在這個then裏面我們能拿到最終的數據
console.log(data);
})
</script>
客戶端需要接口
const express = require("express");
const app = express();
const path = require("path");
const bodyParser = require("body-parser");
app.use(express.static(path.join(__dirname, "")));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//設置允許跨域訪問該服務
app.all("*", function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Headers", "mytoken");
next();
});
app.get("/async1", (req, res) => {
res.send("hello");
});
app.get("/async2", (req, res) => {
if (req.query.info == "hello") res.send("word");
else {
res.send("error");
}
});
app.get("/data", (req, res) => {
res.send("henucm");
});
app.get("/getData", (req, res) => {
res.send("傳遞類型的url傳遞參數" + req.query.id);
});
app.get("/getData/:id", (req, res) => {
res.send("Restful類型的url傳遞參數" + req.params.id);
});
app.delete("/getData/:id", (req, res) => {
res.send("delete請求傳遞參數" + req.params.id);
});
app.delete("/getData", (req, res) => {
res.send("axios delete請求傳遞參數 ," + req.query.id);
});
app.post("/getData", (req, res) => {
res.send("post請求傳遞參數 axios1 ," + req.body.uname + "---" + req.body.pwd);
});
app.put("/getData/:id", (req, res) => {
res.send(
"put請求傳遞參數" +
req.params.id +
"---" +
req.body.uname +
"---" +
req.body.pwd
);
});
app.get("/json", (req, res) => {
res.json({
uname: "lisi",
age: 13,
gender: "male",
});
});
app.listen(3000);
console.log("成功");
app.get("/axios-json", (req, res) => {
res.json({
uname: "lisi",
age: 12,
});
});
fetch API 中的 HTTP 請求
- fetch(url, options).then()
- HTTP協議,它給我們提供了很多的方法,如POST,GET,DELETE,UPDATE,PATCH和PUT
- 默認的是 GET 請求
- 需要在 options 對象中 指定對應的 method method:請求使用的方法
- post 和 普通 請求的時候 需要在options 中 設置 請求頭 headers 和 body
<script type="text/javascript">
/*
Fetch API 調用接口傳遞參數
*/
#1.1 GET參數傳遞 - 傳統URL 通過url ? 的形式傳參
fetch('http://localhost:3000/books?id=123', {
# get 請求可以省略不寫 默認的是GET
method: 'get'
})
.then(function(data) {
# 它返回一個Promise實例對象,用於獲取後臺返回的數據
return data.text();
}).then(function(data) {
# 在這個then裏面我們能拿到最終的數據
console.log(data)
});
#1.2 GET參數傳遞 restful形式的URL 通過/ 的形式傳遞參數 即 id = 456 和id後臺的配置有關
fetch('http://localhost:3000/books/456', {
# get 請求可以省略不寫 默認的是GET
method: 'get'
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data)
});
#2.1 DELETE請求方式參數傳遞 刪除id 是 id=789
fetch('http://localhost:3000/books/789', {
method: 'delete'
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data)
});
#3 POST請求傳參
fetch('http://localhost:3000/books', {
method: 'post',
# 3.1 傳遞數據
body: 'uname=lisi&pwd=123',
# 3.2 設置請求頭
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data)
});
# POST請求傳參
fetch('http://localhost:3000/books', {
method: 'post',
body: JSON.stringify({
uname: '張三',
pwd: '456'
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data)
});
# PUT請求傳參 修改id 是 123 的
fetch('http://localhost:3000/books/123', {
method: 'put',
body: JSON.stringify({
uname: '張三',
pwd: '789'
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data)
});
</script>
fetchAPI 中 響應格式
- 用fetch來獲取數據,如果響應正常返回,我們首先看到的是一個response對象,其中包括返回的一堆原始字節,這些字節需要在收到後,需要我們通過調用方法將其轉換爲相應格式的數據,比如
JSON
,BLOB
或者TEXT
等等
/*
Fetch響應結果的數據格式
*/
fetch('http://localhost:3000/json').then(function(data){
// return data.json(); // 將獲取到的數據使用 json 轉換對象
return data.text(); // // 將獲取到的數據 轉換成字符串
}).then(function(data){
// console.log(data.uname)
// console.log(typeof data)
var obj = JSON.parse(data);
console.log(obj.uname,obj.age,obj.gender)
})
axios
- 基於promise用於瀏覽器和node.js的http客戶端
- 支持瀏覽器和node.js
- 支持promise
- 能攔截請求和響應
- 自動轉換JSON數據
- 能轉換請求和響應數據
axios基礎用法
- get和 delete請求傳遞參數
- 通過傳統的url 以 ? 的形式傳遞參數
- restful 形式傳遞參數
- 通過params 形式傳遞參數
- post 和 put 請求傳遞參數
- 通過選項傳遞參數
- 通過 URLSearchParams 傳遞參數
# 1. 發送get 請求
axios.get('http://localhost:3000/adata').then(function(ret){
# 拿到 ret 是一個對象 所有的對象都存在 ret 的data 屬性裏面
// 注意data屬性是固定的用法,用於獲取後臺的實際數據
// console.log(ret.data)
console.log(ret)
})
# 2. get 請求傳遞參數
# 2.1 通過傳統的url 以 ? 的形式傳遞參數
axios.get('http://localhost:3000/axios?id=123').then(function(ret){
console.log(ret.data)
})
# 2.2 restful 形式傳遞參數
axios.get('http://localhost:3000/axios/123').then(function(ret){
console.log(ret.data)
})
# 2.3 通過params 形式傳遞參數
axios.get('http://localhost:3000/axios', {
params: {
id: 789
}
}).then(function(ret){
console.log(ret.data)
})
#3 axios delete 請求傳參 傳參的形式和 get 請求一樣
axios.delete('http://localhost:3000/axios', {
params: {
id: 111
}
}).then(function(ret){
console.log(ret.data)
})
# 4 axios 的 post 請求
# 4.1 通過選項傳遞參數
axios.post('http://localhost:3000/axios', {
uname: 'lisi',
pwd: 123
}).then(function(ret){
console.log(ret.data)
})
# 4.2 通過 URLSearchParams 傳遞參數
var params = new URLSearchParams();
params.append('uname', 'zhangsan');
params.append('pwd', '111');
axios.post('http://localhost:3000/axios', params).then(function(ret){
console.log(ret.data)
})
#5 axios put 請求傳參 和 post 請求一樣
axios.put('http://localhost:3000/axios/123', {
uname: 'lisi',
pwd: 123
}).then(function(ret){
console.log(ret.data)
})
axios 全局配置
# 配置公共的請求頭
axios.defaults.baseURL = 'https://api.example.com';
# 配置 超時時間
axios.defaults.timeout = 2500;
# 配置公共的請求頭
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
# 配置公共的 post 的 Content-Type
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios 攔截器
- 請求攔截器
- 請求攔截器的作用是在請求發送前進行一些操作
- 例如在每個請求體里加上token,統一做了處理如果以後要改也非常容易
- 請求攔截器的作用是在請求發送前進行一些操作
- 響應攔截器
- 響應攔截器的作用是在接收到響應後進行一些操作
- 例如在服務器返回登錄狀態失效,需要重新登錄的時候,跳轉到登錄頁
- 響應攔截器的作用是在接收到響應後進行一些操作
# 1. 請求攔截器
axios.interceptors.request.use(function(config) {
console.log(config.url)
# 1.1 任何請求都會經過這一步 在發送請求之前做些什麼
config.headers.mytoken = 'nihao';
# 1.2 這裏一定要return 否則配置不成功
return config;
}, function(err){
#1.3 對請求錯誤做點什麼
console.log(err)
})
#2. 響應攔截器
axios.interceptors.response.use(function(res) {
#2.1 在接收響應做些什麼
var data = res.data;
return data;
}, function(err){
#2.2 對響應錯誤做點什麼
console.log(err)
})
async 和 await
- async作爲一個關鍵字放到函數前面
- 任何一個
async
函數都會隱式返回一個promise
- 任何一個
await
關鍵字只能在使用async
定義的函數中使用- await後面可以直接跟一個 Promise實例對象
- await函數不能單獨使用
- async/await 讓異步代碼看起來、表現起來更像同步代碼
# 1. async 基礎用法
# 1.1 async作爲一個關鍵字放到函數前面
async function queryData() {
# 1.2 await關鍵字只能在使用async定義的函數中使用 await後面可以直接跟一個 Promise實例對象
var ret = await new Promise(function(resolve, reject){
setTimeout(function(){
resolve('nihao')
},1000);
})
// console.log(ret.data)
return ret;
}
# 1.3 任何一個async函數都會隱式返回一個promise 我們可以使用then 進行鏈式編程
queryData().then(function(data){
console.log(data)
})
#2. async 函數處理多個異步函數
axios.defaults.baseURL = 'http://localhost:3000';
async function queryData() {
# 2.1 添加await之後 當前的await 返回結果之後纔會執行後面的代碼
var info = await axios.get('async1');
#2.2 讓異步代碼看起來、表現起來更像同步代碼
var ret = await axios.get('async2?info=' + info.data);
return ret.data;
}
queryData().then(function(data){
console.log(data)
})