基于 TS 实现 axios(八)

这一章主要完善接口
目录结构没有进行修改

withCredentials

这个功能是可以携带跨越请求的,默认情况下是自动携带同源 cookie 的 ,但是跨域的时候是不可以进行携带的,将 withCredentials 设置成 true 就可以进行携带了。

types/index.ts

export interface AxiosRequestConfig {
	// ...

    withCredentials?:boolean,
	
    //...
}

core/xhr.ts

// ...
if(timeout) request.timeout = timeout;

if(withCredentials) {
    request.withCredentials = withCredentials;
}
// ...

接改变这点就够了

XSRF

其实就是在 header 中添加 token (后端生成返回的标识)

types/index.ts

export interface AxiosRequestConfig {
	// ...
    xsrfCookieName?:string,
    xsrfHeaderName?:string,
	// ...
}

defaults.ts

const defaults: AxiosRequestConfig = {
	// ...
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
	// ...
}

helpers/url.ts

interface URLOrigin{
    protocol:string,
    host: string,
}


export function isURLsameOrigin(requestURL: string):boolean {
    const parseOrigin = resolverURL(requestURL);
    return (parseOrigin.protocol === currentOrigin.protocol && parseOrigin.host === currentOrigin.host)

}

const urlParsingNode = document.createElement('a');
const currentOrigin = resolverURL(window.location.href);


function resolverURL(url: string): URLOrigin {
    urlParsingNode.setAttribute('href',url);

    const {protocol,host} = urlParsingNode;

    return {
        protocol,
        host,
    }
}

通过 a 标签拿到 protocol (协议)和 host (主机地址)

新建 helpers/cookie.ts

const cookie = {
    read(name: string) : string | null {
        const match = document.cookie.match(new RegExp('(^|;\\s*)(' +  name + ')=([^;]*)'));
        return match ? decodeURIComponent(match[3]) : null;
    }
}

export default cookie;

读取 cookie

core/xhr.ts

// ...
request.ontimeout = function handleTimeout() {
    reject(createError(`Timeout of ${timeout} ms exceeded`,config,'ECONNABORTED',request));
}
// 添加的部分
if((withCredentials || isURLsameOrigin(url)) && xsrfCookieName){
    const xsrfValue = cookie.read(xsrfCookieName);
    if(xsrfValue && xsrfHeaderName) {
        headers[xsrfHeaderName] =
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值