我有这个javascript代码来调用fetch(省略了一些不相关的代码)
const callApi = (endpoint, options) => {
const fullUrl = `${API_ROOT}/${endpoint}`;
return fetch(fullUrl, options)
.then(response =>
response.json().then(json => ({ json, response }))
).then(({ json, response }) => {
if (!response.ok) {
let errorObj = new Error(`ERROR: http error code: ${response.status} - ${response.statusText}`);
throw errorObj;
}
return json;
});
};
export default (dispatch, data) => {
let { endpoint, closeDialogOnSuccess = false, headers = {}, method = 'GET'} = data;
const { actions, fields } = data;
const [ requestAction, successAction, failureAction ] = actions;
const options = { method, headers };
if (fields) {
if(method === 'GET') {
endpoint = endpoint + serialize(_omitBy(fields, _isEmpty));
}
if(method === 'POST' || method === 'PUT') {
options.body = JSON.stringify(fields);
}
}
dispatch(requestAction(data));
return callApi(endpoint, options)
.then((json) => {
dispatch(successAction(json));
if(closeDialogOnSuccess) dispatch(clearDialog());
})
.catch((error) => {
const errorData = data;
let failureActionObject = failureAction(error);
failureActionObject.meta = errorData;
dispatch(failureActionObject);
});
};
它主要起作用,但有两件事困扰我: