在 Axios 中禁用 JSON 解析
Disable JSON parsing in Axios
我有一个 React 应用程序,我希望用户能够在其中上传他随后可以查看的代码文件。
所以自然地,.json 文件也被接受。现在要获取文件内容,我使用 axios 向服务器上的文件发出获取请求。
这适用于除 JSON 文件之外的所有文件,这些文件是自动解析的,因此不能作为字符串使用,而是作为 javascript 对象使用。使用 JSON.stringify
再次将它们转换为字符串会删除所有换行符,所以我不能那样做。
有什么办法可以阻止axios自动解析JSON?
好的,我知道它是如何工作的。您可以通过在配置中传递 transformResponse
数组来禁用响应处理,然后使用该数组代替默认值。您只需提供一个空数组或您需要应用于响应的函数数组,如下所示:
axios.get(URL, {transformResponse: []})
.then(response => {/*response.data is plain text*/});
LuleBes 的回答对我不起作用。起作用的是:
transformResponse: (res) => { return res; },
如:
axios.get(url, {
headers,
transformResponse: (res) => {
// Do your own parsing here if needed ie JSON.parse(res);
return res;
},
responseType: 'json'
}).then(response => {
// response.data is an unparsed string
});
设置以下选项强制 axios 不解析响应:
transformResponse: x => x
用法:
let response = await axios.get('/static/data.json', {
transformResponse: x => x
});
现在 response.data
是 string
,之前是 object
对于我的服务器端渲染 (SSR) 案例,需要明确设置
responseType
参数,根据axios documentation,默认'json'
return axios.get(url, {
transformResponse: res => res,
responseType: 'text'
})
没有这个 'responseType' 参数,当 在测试中工作但在浏览器中失败时,我很困惑。
我有一个 React 应用程序,我希望用户能够在其中上传他随后可以查看的代码文件。
所以自然地,.json 文件也被接受。现在要获取文件内容,我使用 axios 向服务器上的文件发出获取请求。
这适用于除 JSON 文件之外的所有文件,这些文件是自动解析的,因此不能作为字符串使用,而是作为 javascript 对象使用。使用 JSON.stringify
再次将它们转换为字符串会删除所有换行符,所以我不能那样做。
有什么办法可以阻止axios自动解析JSON?
好的,我知道它是如何工作的。您可以通过在配置中传递 transformResponse
数组来禁用响应处理,然后使用该数组代替默认值。您只需提供一个空数组或您需要应用于响应的函数数组,如下所示:
axios.get(URL, {transformResponse: []})
.then(response => {/*response.data is plain text*/});
LuleBes 的回答对我不起作用。起作用的是:
transformResponse: (res) => { return res; },
如:
axios.get(url, {
headers,
transformResponse: (res) => {
// Do your own parsing here if needed ie JSON.parse(res);
return res;
},
responseType: 'json'
}).then(response => {
// response.data is an unparsed string
});
设置以下选项强制 axios 不解析响应:
transformResponse: x => x
用法:
let response = await axios.get('/static/data.json', {
transformResponse: x => x
});
现在 response.data
是 string
,之前是 object
对于我的服务器端渲染 (SSR) 案例,需要明确设置
responseType
参数,根据axios documentation,默认'json'
return axios.get(url, {
transformResponse: res => res,
responseType: 'text'
})
没有这个 'responseType' 参数,当