fetch
is a modern browser native XHR request handler that returns a promise. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
axios
is a library that does the same thing. https://github.com/axios/axios
The way they return data is a little different. Let's compare.
axios.get("/api/game_state").then(
(data) => ...
).catch(
(data) => ...
)
{
"data": {
"entities": [
{
"stuff": "from the server"
},
]
},
"status": 200,
"statusText": "OK",
"headers": {
"date": "Wed, 11 Jul 2018 06:20:41 GMT",
"cache-control": "max-age=0, private, must-revalidate",
"server": "Cowboy",
"content-length": "6823",
"content-type": "application/json; charset=utf-8"
},
"config": {
"transformRequest": {},
"transformResponse": {},
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"headers": {
"Accept": "application/json, text/plain, */*"
},
"method": "get",
"url": "/api/game_state"
},
"request": {}
}
{
"config": {
"transformRequest": {},
"transformResponse": {},
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"headers": {
"Accept": "application/json, text/plain, */*"
},
"method": "get",
"url": "/api/game_stater"
},
"request": {},
"response": {
"data": "<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <title>Phoenix.Router.NoRouteError ... ",
"status": 404,
"statusText": "Not Found",
"headers": {
"date": "Wed, 11 Jul 2018 14:57:22 GMT",
"cache-control": "max-age=0, private, must-revalidate",
"server": "Cowboy",
"content-length": "46621",
"content-type": "text/html; charset=utf-8"
},
"config": {
"transformRequest": {},
"transformResponse": {},
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"headers": {
"Accept": "application/json, text/plain, */*"
},
"method": "get",
"url": "/api/game_stater"
},
"request": {}
}
}
fetch("/api/game_state").then(
(response) => {
if (!response.ok) {
throw Error(response.statusText)
}
return response;
}).then(
(data) => console.log(`fetch:`, data)
).catch(
(data) => console.log(`fetchErr:`, data)
)
{
"entities": [
{
"stuff": "from the server"
},
]
}
Response {
type: "basic",
url: "http://localhost...",
statusText: "Not Found",
status: 404,
redirected: false,
ok: false,
headers: {},
bodyUsed: false,
body: ... ReadableStream ...
}