如何解决RXJS AjaxError 中的错误响应类型
我有一个返回 400 Bad Request
和 Content-Type=text/plain
的 api,但是我无法访问字符串响应,因为 responseType 是 json,这会在解析内容时产生错误,使 { {1}} null,通过查看附加的 response
,XMLHttpRequest
属性显示 responseText
。
所以,我想知道这个 responseType 是如何设置的,以及最终如何将响应作为文本内容访问。该请求是使用 rxjs 中的 [Exception: DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'json'). at XMLHttpRequest.invokeGetter (<anonymous>:2:14)]
方法发出的,唯一的标头集是 ajax.post
。通过查看 source code,您似乎可以自定义此属性,但它似乎也会影响实际上是 JSON 的 Content-Type: "application/json"
,因此我会在成功响应时遇到问题。
我认为代码不是必需的,但我会添加它以查看我实现库的方式是否有问题:
baseApi.ts(只是为了简化应用默认值,因为 rxjs 缺少像 axios 这样的 AjaxResponse
选项,defaultHeaders 只是内容类型):
instance
ApiClient.ts(如您所见,我没有传递任何其他标头)
...
post<ResponseType = unknown,BodyType = unknown>(
url: string,body?: BodyType,headers?: object,) {
return ajax
.post(new URL(url,API_URL).toString(),body,{
...defaultHeaders,...headers,})
.pipe<ResponseType>(map(response => response.response));
},...
有问题的ajax错误:
...
createAlarm: (alarm: Omit<Alarm,"Id">) =>
baseApi.post<Alarm>("/alarms/create",alarm),...
我的 rxjs 版本是 {
"message": "ajax error 400","name": "AjaxError","xhr": {
"onabort": null,"onloadend": null,"onloadstart": null,"onprogress": null,"readyState": 4,"response": null,"responseText": "[Exception: DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'json'). at XMLHttpRequest.invokeGetter (<anonymous>:2:14)]","responseType": "json","responseURL": "http://...:5000/alarms/create","status": 400,"statusText": "Bad Request","timeout": 0,"withCredentials": false
},"request": {
"async": true,"crossDomain": true,"withCredentials": false,"headers": {
"Content-Type": "application/json"
},"method": "POST","url": "http://...:5000/alarms/create","body": "{}"
},"response": null
}
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。