[英]How to Parse Array of JSON Objects using Axios
使用Axios ,我試圖將JSON
數據作為params
傳遞給端點 URL。
我的params
:
const annotations = {
"key": "Book.pdf",
"pages": [
{
"start": "12",
"end": "20"
},
{
"start": "35",
"end": "40"
}
]
}
我的async
功能:
try {
const result = await axios.get(endpoint, {
params: annotations,
paramsSerializer: params => parseParams(params),
headers: {
'Authorization': 'Bearer ' + jwtToken,
'Content-Type': 'application/json'
},
'withCredentials': true
});
} catch (error) {
console.log(error);
}
解析 URL 的函數( GitHub ):
const parseParams = (params) => {
const keys = Object.keys(params);
let options = '';
keys.forEach((key) => {
const isParamTypeObject = typeof params[key] === 'object';
const isParamTypeArray = isParamTypeObject && (params[key].length >= 0);
if (!isParamTypeObject) {
options += `${key}=${params[key]}&`;
}
if (isParamTypeObject && isParamTypeArray) {
params[key].forEach((element) => {
options += `${key}=${element}&`;
});
}
});
return options ? options.slice(0, -1) : options;
};
問題是導致error 500
:
https://api.mysite.com/ConvertBook?key=Book.pdf®ions=[object%20Object]®ions=[object%20Object]
我在網上找不到解決方案,那么如何在 Axios 中解析 JSON 對象數組?
我會在你的參數上使用 JSON.stringify ...
const parseParams = (params) => {
const keys = Object.keys(params);
let options = [];
keys.forEach((key) => {
options.push(`${key}=${encodeURIComponent(JSON.stringify(params[key]))}`);
});
return options.join('&');
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.