return xhr(config) 编译器报错提示

来源:5-11 获取响应数据 - 需求分析+实现

thinktown

2019-08-27

return xhr(config)
编译器报错提示
图片描述

 export interface AxiosRequestConfig {
  url:string
  method?:Method
  data?:any
  params?:any
  headers?:any
  responseType?: XMLHttpRequestResponseType
}
 // "" | "arraybuffer" | "blob" | "document" | "json" | "text"
export interface AxiosResponse {
  data: any
  status: number
  statusText: string
  headers: any
  config: AxiosRequestConfig
  request: any
}

export interface AxiosPromise extends Promise<AxiosResponse> {
}
写回答

2回答

thinktown

提问者

2019-09-05

import { AxiosRequestConfig ,AxiosResponse} from '../types/index'

export default function xhr(config: AxiosRequestConfig) {

    return new Promise ((resolve)=>{
        const { data = null, url, method = 'get' ,headers={},responseType} = config
        
        const request = new XMLHttpRequest()
        
        if(responseType){
            request.responseType = responseType
            }
        request.open(method.toUpperCase(), url, true)
        
        // 监听返回请求
        request.onreadystatechange = function handleLoad() {
            if(request.readyState !== 4){
            return
            }
        
        const responseHeaders = request.getAllResponseHeaders()
            const responseData = responseType && responseType !== 'text' ? request.response : request.responseText
            const response: AxiosResponse = {
            data: responseData,
            status: request.status,
            statusText: request.statusText,
            headers: responseHeaders,
            config,
            request
        }
        resolve(response)
    }
    // data 为空时,删除 content-type
    Object.keys(headers).forEach((name)=>{
        if(data === null && name.toLowerCase() === 'content-type'){
            delete headers[name]
        }else{
            request.setRequestHeader(name,headers[name])
            }
        })
        request.send(data)
    })
}


0
1
ustbhuangyi
你给 xhr 函数的返回值类型标记为 AxiosPromise 再试试
2019-09-06
共1条回复

ustbhuangyi

2019-08-28

你的 xhr 函数怎么写的?

0
1
thinktown
老师,代码我贴出来了。在另一个评论里面。
2019-09-05
共1条回复

下一代前端开发语言 TypeScript从零重构axios

课程从零开始重构功能完整的JS库,是学习造轮子的不二之选!

2631 学习 · 877 问题

查看课程