Это памятка, когда я сравниваю эти два метода.
1. ПОЛУЧИТЬ
принести
fetch(url) .then((res) => { if (!res.ok) { // need error handling here throw Error(); } // need conversion return res.json(); }) .then((data) => { // use this data }) .catch((error) => // error handling ) .finally(() => // this is optional);
аксиомы
Вы можете опустить .get при использовании метода GET
axios.get(url) .then((response) => { const data = response.data; // use this data directly }) .catch((error) => // error handling) .finally(() => // this is optional);
2. ПОСТ
принести
fetch(url, { method: "POST", // you can omit headers nowadays headers: { "Content-Type": "application/json", }, // need conversion body: JSON.stringify( { tag: data.tag, imageUrl: url, }) }) .then((res) => { // need error handling here if (!res.ok) { throw Error(); } }) .catch((error) => { // error handling });
аксиомы
axios.post(url, { // you can put an object directly tag: data.tag, imageUrl: url, }) .then((res) => { // success operations}) .catch((error) => { // error handling });
3. УДАЛИТЬ
принести
fetch(url, { method: "DELETE", }) .then((res) => { // need error handling here if (!res.ok) { throw Error(); } // success operation }) .catch((error) => { // error handling })
аксиомы
axios.delete(url) .then((res) => { // success operation }) .catch((error) => setError("Delete failed")) .finally(() => setLoading(false));
заключение
Наконец-то я понял, почему многие разработчики предпочитают использовать axios, несмотря на то, что нам нужно выполнить громоздкий процесс установки и импорта. Очевидно, что axios намного проще, чем выборка, и мы можем избежать неосознанных ошибок, потому что забываем об ошибках выбрасывания. Поэтому с этого момента я буду использовать axios.
Спасибо, что прочитали.
Я буду рад, если вы дадите мне несколько комментариев, советов или отзывов :)