目錄
瀏覽器http請(qǐng)求
同步?js標(biāo)簽跨域、url
異步ajax、websock協(xié)議
ajax是異步的技術(shù)術(shù)語(yǔ),最早的api是xhr(XMLHttpRequest)
fetch es6 api
axios
封裝axios(無(wú)論用requst還是axios請(qǐng)求都會(huì)生效)
src/utils/request.ts請(qǐng)求/響應(yīng)攔截器封裝
ts
post請(qǐng)求request.post(url)和 通用請(qǐng)求request({url,method:'post'})對(duì)象參數(shù)區(qū)別
src/utils/func.ts工具
ts
SSO(Single Sign-On)單點(diǎn)登錄,一次登陸可訪問(wèn)多個(gè)相互獨(dú)立的程序
正則表達(dá)式
常用字符
前/后向查找:匹配括號(hào)中的內(nèi)容(不包含括號(hào))
泛型(傳參給類型)
src/api/common.ts封裝請(qǐng)求
src/views/components二次封裝請(qǐng)求
基礎(chǔ)知識(shí)回顧
url參數(shù)
location屬性值
同源策略
token和cookie
替換cookie(開發(fā)中模擬不同權(quán)限的用戶)
A.手動(dòng)
B.設(shè)置index.html?
C.瀏覽器擴(kuò)展小程序:一鍵獲取/設(shè)置多個(gè)
web安全
XSS跨站腳本攻擊Cross-Site?Scripting(登陸時(shí)執(zhí)行腳本讀?。?/p>
CSRF跨站請(qǐng)求偽造Cross-site?request?forgery(憑證請(qǐng)求)
SQL注入攻擊(交表單/輸域名?執(zhí)行SQL命令)
DDoS攻擊分布式拒絕服務(wù)?Distributed?Denial?of?Service(請(qǐng)求過(guò)載)
瀏覽器http請(qǐng)求
同步?js標(biāo)簽跨域、url
<img src>,<link href>
異步ajax、websock協(xié)議
ajax是異步的技術(shù)術(shù)語(yǔ),最早的api是xhr(XMLHttpRequest)
fetch es6 api
基于promise,簡(jiǎn)單易用?
axios
- 同構(gòu),即同樣的代碼在nodejs端,瀏覽器端都可用
- 在瀏覽器用xhr,Node.js中使用Node的內(nèi)置http模塊。
// 在瀏覽器中,根據(jù)其Content-Type頭信息,自動(dòng)轉(zhuǎn)換數(shù)據(jù)
axios.get('/api/data').then(response => {
// response.data 將是一個(gè)JavaScript對(duì)象
});
// 在Node.js中手動(dòng)設(shè)置響應(yīng)數(shù)據(jù)類型
axios.get('/api/data', { responseType: 'json' }).then(response => {
// response.data 將是一個(gè)JavaScript對(duì)象
});
- axios 新版本也支持了fetch
- 第三方庫(kù)都是基于原生API的,所以axios也還是基于xhr的
【JavaScript】爆肝 2 萬(wàn)字!一次性搞懂 Ajax、Fetch 和 Axios 的區(qū)別~ - 掘金
封裝axios(無(wú)論用requst還是axios請(qǐng)求都會(huì)生效)
axios常用類型
src/utils/request.ts請(qǐng)求/響應(yīng)攔截器封裝
import service from 'axios'
//service是一個(gè)根據(jù)需要自行命名,通過(guò)axios庫(kù)創(chuàng)建的HTTP請(qǐng)求服務(wù)實(shí)例
import { handleSSO,errorMsgTips } from '@/utils/func'
import router from '@/router/index'
// 請(qǐng)求攔截器
service.interceptors.request.use(
(config: any) => {
// 在請(qǐng)求頭中添加X(jué)MLHttpRequest字段
config.headers['X-Requested-With'] = 'XMLHttpRequest'
return config
},
(error: any) => {
console.log('request:', error) // 用于調(diào)試的錯(cuò)誤信息
return Promise.reject(error)
}
)
// 響應(yīng)攔截器
service.interceptors.response.use(
(response: { data: any; config: HttpRequestConfig }) => {
const resData = response.data || {}
if (resData.code === 302) {
// 如果響應(yīng)碼為302,進(jìn)行頁(yè)面重定向到指定鏈接
window.location.href = `https://www.example.com/path/to/resource.html/domain=${location.host}&req=${encodeURIComponent(location.pathname)}&protocol=https${location.hash}`
} else if (resData.code == 0 || resData.code == 200) {
// 如果響應(yīng)碼為0或200,則直接返回響應(yīng)數(shù)據(jù)
return resData
} else if (resData.code == 4004) {//自定義響應(yīng)碼
// 如果響應(yīng)碼為4004,說(shuō)明沒(méi)有權(quán)限,跳轉(zhuǎn)至無(wú)權(quán)限頁(yè)面
router.push({
path: '/notPermission'
})
} else {
// 其他情況下,顯示錯(cuò)誤提示消息
errorMsgTips(resData.message || '接口錯(cuò)誤,請(qǐng)稍后重試')
}
},
(error: any) => {
if (service.isCancel(error)) {
console.log('取消請(qǐng)求 error -> ', error)
return
}
if (error && error.response && error.response.status === 302) {
if (process.env.NODE_ENV === 'development') {
// 如果是開發(fā)環(huán)境,并且錯(cuò)誤碼為302,顯示替換SSO_SESSION_ID的提示
errorMsgTips('請(qǐng)?zhí)鎿QCookies里的SSO_SESSION_ID')
return
} else {
// 非開發(fā)環(huán)境下,進(jìn)行單點(diǎn)登錄重定向
window.location.href = handleSSO('login')
}
} else if (error && error.stack.includes('timeout')) {
// 如果錯(cuò)誤信息中包含"timeout",顯示接口超時(shí)錯(cuò)誤提示
errorMsgTips('接口超時(shí)')
return
} else if (error && error.stack.includes('Network')) {
// 如果錯(cuò)誤信息中包含"Network",顯示網(wǎng)絡(luò)異常錯(cuò)誤提示
errorMsgTips('網(wǎng)絡(luò)異常')
return
}
return Promise.reject(error)
}
)
export default service
ts
import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
import { handleSSO, errorMsgTips } from '@/utils/func';
import router from '@/router/index';
// 請(qǐng)求攔截器
axios.interceptors.request.use(
(config: AxiosRequestConfig) => {
// 在請(qǐng)求頭中添加X(jué)MLHttpRequest字段
config.headers['X-Requested-With'] = 'XMLHttpRequest';
return config;
},
(error: AxiosError) => {
console.log('request:', error); // 用于調(diào)試的錯(cuò)誤信息
return Promise.reject(error);
}
);
// 響應(yīng)攔截器
axios.interceptors.response.use(
(response: AxiosResponse) => {
const resData = response.data || {};
if (resData.code === 302) {
// 如果響應(yīng)碼為302,進(jìn)行頁(yè)面重定向到指定鏈接
window.location.href = `https://www.example.com/path/to/resource.html/domain=${location.host}&req=${encodeURIComponent(location.pathname)}&protocol=https${location.hash}`;
} else if (resData.code == 0 || resData.code == 200) {
// 如果響應(yīng)碼為0或200,則直接返回響應(yīng)數(shù)據(jù)
return resData;
} else if (resData.code == 4004) { //自定義響應(yīng)碼
// 如果響應(yīng)碼為4004,說(shuō)明沒(méi)有權(quán)限,跳轉(zhuǎn)至無(wú)權(quán)限頁(yè)面
router.push({
path: '/notPermission'
});
} else {
// 其他情況下,顯示錯(cuò)誤提示消息
errorMsgTips(resData.message || '接口錯(cuò)誤,請(qǐng)稍后重試');
}
return Promise.reject(resData);
},
(error: AxiosError) => {
if (axios.isCancel(error)) {
console.log('取消請(qǐng)求 error -> ', error);
return;
}
if (error && error.response && error.response.status === 302) {
if (process.env.NODE_ENV === 'development') {
// 如果是開發(fā)環(huán)境,并且錯(cuò)誤碼為302,顯示替換SSO_SESSION_ID的提示
errorMsgTips('請(qǐng)?zhí)鎿QCookies里的SSO_SESSION_ID');
return;
} else {
// 非開發(fā)環(huán)境下,進(jìn)行單點(diǎn)登錄重定向
window.location.href = handleSSO('login');
}
} else if (error && error.stack.includes('timeout')) {
// 如果錯(cuò)誤信息中包含"timeout",顯示接口超時(shí)錯(cuò)誤提示
errorMsgTips('接口超時(shí)');
return;
} else if (error && error.stack.includes('Network')) {
// 如果錯(cuò)誤信息中包含"Network",顯示網(wǎng)絡(luò)異常錯(cuò)誤提示
errorMsgTips('網(wǎng)絡(luò)異常');
return;
}
return Promise.reject(error);
}
);
export default axios;
post請(qǐng)求request.post(url)和 通用請(qǐng)求request({url,method:'post'})對(duì)象參數(shù)區(qū)別
具體請(qǐng)求方式只能使用指定的請(qǐng)求方法,如 post
、get
、put
等。
axios.post(url, data, {
responseType: 'json' // 設(shè)置響應(yīng)的數(shù)據(jù)類型為 JSON
})
.then(response => {
// 處理響應(yīng)數(shù)據(jù)
console.log(response.data);
})
.catch(error => {
// 處理請(qǐng)求錯(cuò)誤
console.error(error);
});
src/utils/func.ts工具
/**
* 清除會(huì)話
* @param
*/
function clearSession() {
//匹配不包含空格和分號(hào)的字符,該字符后面必須跟著一個(gè)等號(hào)。這會(huì)返回一個(gè)由cookie鍵組成的數(shù)組。
const keys = document.cookie.match(/[^ =;]+(?=\=)/g)
if (keys) {
for (let i = keys.length; i--; )
//) 創(chuàng)建了一個(gè)代表時(shí)間戳 0 的 JavaScript Date 對(duì)象,并將其轉(zhuǎn)換為 UTC 字符串。
//這個(gè)時(shí)間對(duì)應(yīng)于 1970 年 1 月 1 日 協(xié)調(diào)世界時(shí) (UTC) 時(shí)間 00:00:00。
document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
}
sessionStorage.clear()
localStorage.clear()
}
/**
* SSO登入登出
* @param SSOtype
* login登入
* logout登出
*/
export function handleSSO(SSOtype: string): string {
const hostStr = 'passport.example.com'
clearSession()
return `https://${hostStr}/${SSOtype}?service=` + encodeURIComponent(window.location.origin)
}
export function errorMsgTips(msg: string) {
window.$message.error(msg)
}
ts
/**
* 清除會(huì)話
*/
function clearSession(): void {
const keys: string[] | null = document.cookie.match(/[^ =;]+(?=\=)/g);
if (keys) {
for (let i = keys.length; i--; ) {
document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString();
}
}
sessionStorage.clear();
localStorage.clear();
}
/**
* SSO登入登出
* @param SSOtype
* login 登入
* logout 登出
*/
export function handleSSO(SSOtype: 'login' | 'logout'): string {
const hostStr = 'passport.example.com';
clearSession();
return `https://${hostStr}/${SSOtype}?service=` + encodeURIComponent(window.location.origin);
}
export function errorMsgTips(msg: string): void {
window.$message.error(msg);
}
SSO(Single Sign-On)單點(diǎn)登錄,一次登陸可訪問(wèn)多個(gè)相互獨(dú)立的程序
通??縯oken/cookie實(shí)現(xiàn)
正則表達(dá)式
常用字符
·匹配除換行字符外的任何單個(gè)字符
*匹配前一個(gè)字符零或多次。例如,"zo*”與"z”或"zoo”匹配。
+匹配前一個(gè)字符一次或多次。例如,"zo+"與"zoo”匹配,但和"z”不匹配。
?匹配前一個(gè)字符零或一次。例如,"a?ve?”和"never"中的“"ve”匹配。
x|y 匹配x或y
{n}匹配n次。n是非負(fù)整數(shù)
{n,} n是一個(gè)非負(fù)整數(shù)。至少匹配n次。例如,"o{2,)"和"Bob”中的"o”不匹配,但和"foooood"中的所有o匹配。"o{1}”與"o+”等效。"o{0,}”和"o*”等效。
{n,m}m和n是非負(fù)整數(shù)。至少匹配n次而至多匹配 m次。例如,"o{1,3]"和"fooooood”中的前三個(gè)o匹配。"o{0,1}”和“o?”等效。
[xyz]匹配括號(hào)內(nèi)的任一字符。例如,"[abc]"和"plain”中的"a”匹配。
[^xyz]匹配非括號(hào)內(nèi)的任何字符。例如,"[^abc]"和“plain”中的"p”匹配。
[a-z]字符范圍。和指定范圍內(nèi)的任一字符匹配。例如,"[a-z]”匹配"a"到"z"范圍內(nèi)的任一小寫的字母表字符。
[^m-z]否定字符范圍。匹配不在指定范圍內(nèi)的任何字符。例如,"[m-z]”匹配不在"m"到"z"范圍內(nèi)的任何字符。
前/后向查找:匹配括號(hào)中的內(nèi)容(不包含括號(hào))
后向查找:(?<=exp)是以exp開頭的字符串, 但不包含本身.
前向查找:(?=exp)就匹配為exp結(jié)尾的字符串, 但不包含本身.
負(fù)后向查找:(?<!exp)?,在之前被指定的子表達(dá)式不能被匹配到。
負(fù)前向查找::(?!exp),在之后被指定的子表達(dá)式不能被匹配到。
正向先行斷言?(?=\=)
?表示在匹配等號(hào)?=
?前面的位置進(jìn)行斷言,即正向這個(gè)位置后面必須跟著等號(hào)?=
?才能進(jìn)行匹配。這種斷言不會(huì)消耗實(shí)際的字符。
前向查找?(?==)
?表示匹配等號(hào)?=
,并且把等號(hào)?=
?包含在匹配結(jié)果中。這種查找會(huì)消耗等號(hào)?=
?這個(gè)字符。
泛型(傳參給類型)
function printValue<T>(value: T): void {
console.log(value);
}
// 使用泛型參數(shù)傳遞參數(shù)類型
printValue<string>("Hello, World!"); // 輸出: Hello, World!
printValue<number>(42); // 輸出: 42
printValue<boolean>(true); // 輸出: true
src/api/common.ts封裝請(qǐng)求
import request from '@/utils/request'
const baseUrl = process.env.NODE_ENV === 'development' ? '/test' : ''
const mock = false
// 查看自己信息接口
export const commonQuery = (data: any) => {
const url = mock ? `${baseUrl}/common/query` : `${baseUrl}/mock/query`
return request.post(url, data)
}
// 查看自己信息接口
export const getUserInfo = () => {
const url = `${baseUrl}/menu/userInfo`
return request.get(url)
}
//具體使用那種 與后端設(shè)置相關(guān)
// request.post(url, data)與
// request({
// url,
// method: 'post',
// params: data
// })
// }
// 都是返回promise對(duì)象
src/views/components二次封裝請(qǐng)求
import * as API from "@/api/common"
import { debounce } from 'lodash'
...
// 業(yè)績(jī)指標(biāo)list
baseIndexQuaryScoreIndex = debounce(this.baseIndexQuaryScoreIndexAPI, 100)
async baseIndexQuaryScoreIndexAPI(type: string) {
try {
const res = await API.getQuery()
if (res && res.code == 200) {
this.quaryScoreIndexList = res.data || []
} else {
this.$message.error(res.msg || '接口錯(cuò)誤')
}
} catch (e: any) {
this.$message.error(e.msg || '接口錯(cuò)誤')
}
}
//await API.getQuery()等價(jià)于API.getQuery().then
baseIndexQuaryScoreIndex() {
API.getQuery().then((res: any) => {
if (res && res.code == 200) {
this.quaryOtherIndexList = res.data || []
} else {
this.$message.error(res.msg || '接口錯(cuò)誤')
}
}).catch((e: any) => {
this.$message.error(e.msg || '接口錯(cuò)誤')
})
}
//調(diào)用
this.baseIndexQuaryScoreIndex()
基礎(chǔ)知識(shí)回顧
url參數(shù)
http://example.com/page?param1=value1¶m2=value2#section1
? | 分隔實(shí)際的URL和參數(shù) |
& | URL中指定的參數(shù)間的分隔符 |
= | 左邊為參數(shù)名、右邊參數(shù)值 |
# | 錨點(diǎn)(Anchor),用于標(biāo)識(shí)文檔中的特定位置或元素, 僅在客戶端使用,并且由瀏覽器處理,不發(fā)送到服務(wù)器 指示瀏覽器滾動(dòng)到具有 |
location屬性值
window的全局對(duì)象,表示當(dāng)前頁(yè)面http://www.example.com/path/index.html
window.location.href:獲取/設(shè)置 url
window.location.orgin:協(xié)議、主機(jī)名和端口號(hào)部分
//https://www.example.com:8080/page.html
// :// :
//https%3A%2F%2Fwww.example.com%3A8080。
encodeURIComponent(window.location.origin)
//encodeURIComponent用于將字符串中的特殊字符(空格、&、+、= 、?)轉(zhuǎn)換為編碼形式,確保URL中不包含任何無(wú)效字符
//查詢參數(shù)時(shí) 或者 動(dòng)態(tài)參數(shù)時(shí) 需要encodeURIComponent
const url = 'https://example.com/api?param=' + encodeURIComponent(queryParam);
window.location.href =`https://www.example.com/path/to/resource.html/domain=${location.host}&req=${encodeURIComponent(location.pathname)}&protocol=https${location.hash}`
window.location.protocol: 協(xié)議http
window.location.host:主機(jī)+端口(host:8080)/IP地址(127.123.32.1唯一)/域名(www.example.com助記)
window.location.hostname:主機(jī)host
window.location.port:端口8080
window.location.pathname: 資源路徑path/index.html,資源index.html
window.location.hash:
window.location.search: 搜索
var searchParams = new URLSearchParams(window.location.search);
console.log(searchParams.get('name')); // 輸出 "John"
同源策略
同源/域:顧名思義,域名包括前綴都要相同,自然也包括端口號(hào)
但是cookie從端口號(hào)開始就可以不同
跨域請(qǐng)求默認(rèn)情況下不會(huì)攜帶 Cookie。
然而,可以通過(guò)設(shè)置 CORS(跨源資源共享)頭部來(lái)允許攜帶 Cookie 進(jìn)行跨域請(qǐng)求
token和cookie
憑證 | token | cookie |
跨域 | token 完全由應(yīng)用管理,所以它可以避開同源策略 |
服務(wù)器端生成管理,不能跨域 |
與session | 移動(dòng)端對(duì) cookie 的支持不是很好,所以移動(dòng)端常用的是 token |
session 需要基于 cookie 實(shí)現(xiàn) |
替換cookie(開發(fā)中模擬不同權(quán)限的用戶)
A.手動(dòng)
B.設(shè)置index.html?
<!DOCTYPE html>
<html lang="">
<head>
...
<div id="app"></div>
<script>
document.cookie = 'sso_ticket=xx'
</script>
</body>
</html>
C.瀏覽器擴(kuò)展小程序:一鍵獲取/設(shè)置多個(gè)
獲取項(xiàng)目網(wǎng)頁(yè)中的cookies,然后在本地的項(xiàng)目網(wǎng)頁(yè)中設(shè)置
web安全
XSS跨站腳本攻擊Cross-Site?Scripting(登陸時(shí)執(zhí)行腳本讀?。?/h4>
解決:文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-510098.html
- url參數(shù)使用encodeURIComponent方法轉(zhuǎn)義
- 盡量不用InnerHtml插入HTML內(nèi)容
CSRF跨站請(qǐng)求偽造Cross-site?request?forgery(憑證請(qǐng)求)
解決:添加驗(yàn)證碼、使用token
SQL注入攻擊(交表單/輸域名?執(zhí)行SQL命令)
解決:表單輸入時(shí)通過(guò)正則表達(dá)式將一些特殊字符進(jìn)行轉(zhuǎn)換文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-510098.html
DDoS攻擊分布式拒絕服務(wù)?Distributed?Denial?of?Service(請(qǐng)求過(guò)載)
解決:
- 限制單IP請(qǐng)求頻率。
- 檢查特權(quán)端口的開放
到了這里,關(guān)于前端開發(fā)中的ajax請(qǐng)求、axios封裝的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!