这一章主要完善接口
目录结构没有进行修改
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] =