如果使用Axios从API获取XML响应而返回二进制数据,则可能需要设置responseType。在Axios请求中,使用responseType配置选项以指定响应数据的类型。默认情况下,responseType是JSON,但可以设置为其他类型,例如'blob','arraybuffer'等。因此,将responseType设置为'blob'或'arraybuffer'可能会解决该问题。这是一个示例代码:
axios.get('https://example.com/api/data', {
responseType: 'blob'
})
.then(function (response) {
// handle success
var xmlData = new DOMParser().parseFromString(response.data, "text/xml");
console.log(xmlData);
})
.catch(function (error) {
// handle error
console.log(error);
});
在这个例子中,Axios请求被设置了responseType:'blob'。当请求成功时,响应数据存储在response.data中,并将其用于解析XML数据。最终,将XML数据打印在控制台上。
如果知道返回的数据确实是XML数据,则可以将responseType直接设置为'xml':
axios.get('https://example.com/api/data', {
responseType: 'xml'
})
.then(function (response) {
// handle success
console.log(response.data);
})
.catch(function (error) {
// handle error
console.log(error);
});
在这个例子中,Axios请求被直接设置为responseType:'xml'。在成功的请求中,XML响应数据存储在response.data中,并将其打印在控制台上。
下一篇:axios返回HTML