Understanding a tutorial: Using axios.get()

I'm following a tutorial that uses Express JS to create a server and integrates it with some 'static' resources (html, css, js).. showing how app.get(), app.post() work with a form etc (pic 1 & 2) There are 2 'versions' of the form that the tutorial goes over. One of them, (the index.html), links the form to the server, in app.js, with a method = POST. (pic 3) There, we're using a require() to get a people array out of a local file (data.js), and in our app.post using that info to test against the user's form input. (pic 1) The second version of the form (in javascript.html), links the form to javascript (same-page script tags). This is the one I'm confused about. Here, he uses an axios library and axios.get().. in order to somehow also grab that same people array from the same local data.js file, and then display all of the 'people' array names on the page, in a div container called "result".
<script>
const result = document.querySelector('.result')

const fetchPeople = async () => {
try {
const { data } = await axios.get('/api/people')

const people = data.data.map((person) => {
return `<h5>${person.name}</h5>`
})
result.innerHTML = people.join('')
} catch (error) {
result.innerHTML = `<div class="alert alert-danger">Can't Fetch Data</div>`
}
}
<script>
const result = document.querySelector('.result')

const fetchPeople = async () => {
try {
const { data } = await axios.get('/api/people')

const people = data.data.map((person) => {
return `<h5>${person.name}</h5>`
})
result.innerHTML = people.join('')
} catch (error) {
result.innerHTML = `<div class="alert alert-danger">Can't Fetch Data</div>`
}
}
The part I don't understand is the const { data } = await axios.get('/api/people') "/api/people", in the app.js, was the URL we'd set to display already gotten data (the "people" array). But here, in this javascript, at no point yet have we 'already gotten' that people array data. I can't tell what the axios.get(), const { data } = await axios.get('/api/people') , is doing. Is it going to the app.js-setup URL in order to retrieve the 'people' data (as opposed to getting it from the local folder itself)?
14 Replies
Jochem
Jochem•2y ago
axios.get is performing an HTTP GET request to /api/people and returning the result after some parsing it's doing the same thing fetch would do, but it's a library with potentially some extra features, which also predates fetch especially in nodejs which only got native fetch support recently
thethingisback
thethingisbackOP•2y ago
so like with the app.js 'get' request.. we had to source the data to be responded with (the 'people' array) we had to actually first require() the doc housing that info, and then we included it as the response to the get request... But in the axios.get().. how is it getting and returning that 'people' array info?... Its assigned to a const = {data}, and of course the local file is data.js.. but where does this 'getting people array' happen?
Jochem
Jochem•2y ago
axios.get is the method that does HTTP requests, so it's like typing <yourdomain>/api/people in your browser. That probably produces a bunch of JSON data, from where you defined that endpoint. Axios returns some kind of object that contains a data property, which is assigned to the newly defined data (const {data} is called destructuring syntax, and will take whatever is to the right of the assignment operator and take the data property from that and assign it to a const called data in the local scope) There's nothing clever happening, it's literally just doing an HTTP request and whatever is on the other side of that request is responding with the data based on how it's set up. Axios is not going to read your code or figure out any shortcuts or whatever
thethingisback
thethingisbackOP•2y ago
okay so it's destructuring information that is a*already stored *at /api/people... meaning that information has to already be at that URL, right? So doesn't that imply that we didn't set up the response? since the data already there at that URL? it doesn't seem like we're controlling the get request's response here
Jochem
Jochem•2y ago
I'm not sure what you mean. You could fill any endpoint of any api in that axios.get and it would fetch data from there. It's irrelevant that it's accessing the same application its in the app.get call is what's setting up the endpoint you're accessing, and it's sending whatever is in people (which is the data from ./data) back whenever someone accesses it destructuring is just syntax shorthand, you could rewrite
const {data} = axios.get(...);
const {data} = axios.get(...);
as
const data = axios.get(...).data;
const data = axios.get(...).data;
or
const tmp = axios.get(...);
const data = tmp.data;
const tmp = axios.get(...);
const data = tmp.data;
thethingisback
thethingisbackOP•2y ago
I get destructuring.. Let me try an analogy The get request is an empty box. In app.js... we declare what the person has to say in order to receive what's in the box (the URL).. AND we have to get the thing to put in the box, the thing to respond with, so that when the person says the thing (provides the URL), we have already gotten the thing to give to them. We have to do both parts.. specify the URL, AND also procure the thing to be responded with (the 'data') In the axios JS, there is no part where I've gotten the thing (data) to be responded with. I've specified what the person must say in order to get what's in the box... (specified the URL).. but I have not actually gotten the thing that has to be in the box at the time that it's requested.. the app.js gets that info with the require() actually goes and gets that file and destructures it, and so it has the thing to respond to the GET request with in axios, we're just specifying the URL.. and magically getting information? or is axios.get getting the information that's already been put at that URL by app.js?
Jochem
Jochem•2y ago
this is where you've gotten the data to be responded with
Jochem
Jochem•2y ago
the "magic" is that it does an HTTP request that gets handled by app.js, so not really magic at all
thethingisback
thethingisbackOP•2y ago
oh okay so axios.get() is not "setting up" the GET request - how it should be responded to etc - "how a GET request should be responded to" is still be controlled by app.js, not by the axios.get() axios.get() is just saying "make a get request to the app.js server" if i didn't have the app.get() set up already, then the axios.get() would not work
Jochem
Jochem•2y ago
correct app.get is defining the route, axios.get is accessing the route axios is just fancy fetch
thethingisback
thethingisbackOP•2y ago
gotcha gotcha ok much appreciated as always sorry for the confusion
Jochem
Jochem•2y ago
glad to help 🙂
thethingisback
thethingisbackOP•2y ago
so I'm now doing the axios.post() from a form submit (click event listener in JS). This is the javascript.
const btn = document.querySelector('.submit-btn')
const input = document.querySelector('.form-input')
const formAlert = document.querySelector('.form-alert')
btn.addEventListener('click', async (e) => {
e.preventDefault()
const nameValue = input.value

try {
** const { data } = await axios.post('/api/people',{name: nameValue})**
const h5 = document.createElement('h5')
h5.textContent = data.person
result.appendChild(h5)
} catch (error) {
// console.log(error.response)
formAlert.textContent = error.response.data.msg
}
input.value = ''
})
const btn = document.querySelector('.submit-btn')
const input = document.querySelector('.form-input')
const formAlert = document.querySelector('.form-alert')
btn.addEventListener('click', async (e) => {
e.preventDefault()
const nameValue = input.value

try {
** const { data } = await axios.post('/api/people',{name: nameValue})**
const h5 = document.createElement('h5')
h5.textContent = data.person
result.appendChild(h5)
} catch (error) {
// console.log(error.response)
formAlert.textContent = error.response.data.msg
}
input.value = ''
})
And then from app.js, I listen for an POST request from '/api/people', which I assume receives {name: nameValue} as its req.body
app.post('/api/people',(req, res)=>{
// console.log(req.body)
res.status(201).send('success');
})
app.post('/api/people',(req, res)=>{
// console.log(req.body)
res.status(201).send('success');
})
In the tutorial, at this point, he's able to look in the network tab 'headers' section and see the POST request. However, when I submit the form, I'm not seeing the request come in on my network headers tab
Jochem
Jochem•2y ago
any errors in the console?
Want results from more Discord servers?
Add your server