1. 前言
簡單的總結(jié)下前端的請求方式
2.服務(wù)端
服務(wù)端就選用node
任TA前端幾路來,我后端只一路去
五種請求方式的前端,后端都是一套
// express 極簡的web開發(fā)框架
const express = require('express')
var app = express()
// 靜態(tài)資源目錄,前端代碼放這里
app.use(express.static(__dirname+"/public"))
// 中間件 處理post請求參數(shù)
app.use(express.json())
app.use(express.urlencoded({extended:true}))
//get請求的登錄接口
app.get("/login",(req,res) => {
res.json({
code:1000,
msg:"get-成功",
name: req.query.name,
psw: req.query.password
})
})
// post請求的注冊
app.post("/register",(req,res) => {
res.json({
code:1000,
msg:"post-成功",
name: req.body.name,
psw: req.body.password
})
})
// jsonp
app.get("/jsonp",(req,res) => {
res.jsonp({code:200,msg:"jsonp成功"})
})
app.listen(7788,()=>{
console.log("7788服務(wù)啟動");
})
3.表單請求-get
<form action="/login" method="get">
<input type="text" name="name">
<input type="text" name="password">
<input type="submit" value="get">
</form>
4. 表單請求-post
<form action="/register" method="post">
<input type="text" name="name">
<input type="text" name="password">
<input type="submit" value="post">
</form>
5. 原生ajax-get
簡易寫法
var xhr = new XMLHttpRequest();
xhr.open("GET", `/login?name=${userName.value}&password=${password.value}`)
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log("ajax", xhr.responseText);
}
}
6.原生ajax-post
var xhr = new XMLHttpRequest();
xhr.open("POST", "/register")
//設(shè)置請求頭 等配置信息
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.send(`name=${userName.value}&password=${password.value}`)
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText)
}
}
7. jQ-get
$.ajax({
type: "get",
url: "/login",
data: { name: userName.value, password: password.value },
success: function (response) {
console.log("jq-get:", response)
}
});
8.jQ-post
$.ajax({
type: "post",
url: "/register",
data: { name: userName.value, password: password.value },
success: function (response) {
console.log("jq-get:", response)
}
});
9. axios-get
注意的就是
axios
的get
請求參數(shù){params:{參數(shù)}}
外面多了一層
axios.get("/login",{params: {
name: userName.value,
password: password.value
}})
.then(res => {
console.log("axios-get",res.data)
})
.catch(err => {
console.error("axios-get-err:",err);
})
10. axios-post
axios.post("/register", {
name:userName.value,
password:password.value
})
.then(res => {
console.log("axios-post",res.data)
})
.catch(err => {
console.error("axios-post-err",err);
})
第三個參數(shù)是配置信息,不需要配置就不填
{
headers: { "Content-Type": "application/x-www-form-urlencoded" }
}
11. fetch -get
fetch(`/login?name=${userName.value}&password=${password.value}`).then((res) =>{
res.json().then(data=>{
console.log("響應(yīng)數(shù)據(jù):",data)
})
})
12 fetch-post
fetch("/register",{
method: "POST",
body: JSON.stringify({
name:userName.value,
password:password.value
}),
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
}).then((res) =>{
res.json().then(data=>{
console.log("響應(yīng)數(shù)據(jù):",data)
})
})
13.jsonp
jsonp 只是解決前端跨域的一種非標(biāo)準(zhǔn)的方式,
所以axios
和fetch
原生不支持jsonp
,
通常還是后端解決跨域
13.1 原生ajax實(shí)現(xiàn)
<script>
function getData(res){
console.log("Res----------:",res);
}
</script>
<script src="http://127.0.0.1:7788/jsonp?callback=getData"></script>
回調(diào)函數(shù)寫到 腳本標(biāo)簽的上邊
實(shí)際工作中 都是動態(tài)創(chuàng)建script
標(biāo)簽 ,拼接url
參數(shù)
一般動態(tài)創(chuàng)建
script
標(biāo)簽
let showMsg = (res) => {
console.log("jsonp 結(jié)果:", res)
}
let jsonpFn = () => {
let script = document.createElement("script")
script.src = "http://127.0.0.1:7788/jsonp?callback=showMsg"
document.body.appendChild(script)
//發(fā)完請求 就刪掉 避免重復(fù)創(chuàng)建
document.body.removeChild(script)
}
13.2 jQ ajax實(shí)現(xiàn)
$.ajax({
type: "get",
url: "http://127.0.0.1:7788/jsonp",
data: {},
dataType: "jsonp",
success: function (response) {
console.log("response:",response);
}
});
重點(diǎn)就是
dataType
設(shè)置為jsonp
14.fetch-xhr
工具 | 本質(zhì) | 優(yōu)劣 |
---|---|---|
原生XHR | let xhr = new XMLHttpRequest() | 瀏覽器支持的原生技術(shù); 基于回調(diào)方式處理響應(yīng) |
jQ ajax | XHR的進(jìn)一步封裝而已 | 比原生簡單; 基于回調(diào)方式處理響應(yīng) |
Axios | XHR的進(jìn)一步封裝而已 | 比原生簡單; 基于Promise處理響應(yīng);可以排隊(duì),并發(fā),撤銷 |
NG httpClient | XHR的進(jìn)一步封裝而已 | 比原生簡單; 基于觀察者模式 方式處理響應(yīng);可以排隊(duì),并發(fā),撤銷 |
Fetch | 不再是XHR,是W3C 提出的新技術(shù),希望是替代 XHR
|
比XHR 從根本上更加先進(jìn);天然基于Promise ;兼容性還有點(diǎn)問題 |