首先是请求
axios({
method: 'post',
url: '/base/post',
data: {a: 1,b: 2}
})
中间的ts配置都是按老师的写法写的,没有报错,语法也没问题,并且和老师代码进行了对照
下面是xhr.ts
export default function xhr(config: AxiosRequestConfig): AxiosPromise {
return new Promise((resolve, reject) => {
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
}
console.log("打印原始XMLHttpRequest",request)
// 这里打印的request里面responseType是 ""
// 打印的request里面response 是 "{}"
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)
}
Object.keys(headers).forEach(name => {
if (data === null && name.toLowerCase() === 'content-type') {
delete headers[name]
} else {
request.setRequestHeader(name, headers[name])
}
})
console.log("responseType",responseType) // 这里是undefined,未指定的情况下应该也没错
console.log("send(data)",data) // 这里 {"a":1,"b":2}
request.send(data)
})
}
再下面是server
router.post('/base/post', function(req, res) {
res.json(req.body)
})
最终猜测server传回去的req.body很有可能就是 {} ,但是send之前已经确保打印了,不明白为什么,本来想在server里打印下,但是可惜控制台没输出