Subtitles section Play video Print subtitles [BELL RINGING] Welcome back. I don't know what you did since the last video, but I went and got a haircut. Thank you. In this video, I am going to do something important, a key feature here. What I want to do is take data from the client, the latitude and longitude, and send it to the server and have the server receive it. Ultimately, the point of this is for the server to eventually save that to a database. But I'm not there yet. I just want to say, the client executes its own client side JavaScript, gets the latitude and longitude, and sends that data to the server and the server can just console log it. I'm going to need to look at three things in order to do this, I'm going to need to look at a concept known as a routing, how do I set up a route in express. This is the place, the end point for the API, the address at which I will send the data to and later also make a request to receive some data. I need to look at adding JSON parsing to express. I need the route when it receives data to understand that data as JSON and make it readable in my code. And then I also need to look at adapting the fetch function to specify a POST request, a request that is posting data or sending data to the server. Let's start with the route. So I want to set up a route on my server. So the way that I do that is by specifying this particular route, will either be a Get or a POST. In this case I expect a POST request, so I am going to go and say app.post. Now, once I have a post, I want to specify both the address where I want to receive that POST, as well as a callback function where I'm going to look at the information coming in and send a response back. So let's set up that address, let's set up the endpoint for this particular route. Where I want to receive the post. And I could call it anything I want, like Unicorn, Cupcake, Rainbow. Let's call it Rainbow. All right, I'll give it a name that's maybe more appropriate. I'm going to call it API. API because what I'm really doing here is setting up an application programming interface. This is my API for clients to send data to me. Next, I'm going to set up a callback, request response, and I'm using the ES6, JavaScript ES6 arrow syntax. Just sort of a nice, clean way of putting this in here. So the function is here and it has two arguments, request and response. The request variable hold everything that's contained within that request, all the data that's being sent, any information I need to know about that particular client that's sending the information. The response is a variable that I can use to send things back to the client. So I'm going to need ultimately to do stuff there, but for right now, I'm just going to say console.log request, and I'm just going to leave it like that because let's at least see if we can get this working and see if we can see something console log there. The next step is to have my client send something to this particular endpoint with a post. I can now move over to the client code and setup the post itself using Fetch. So I want to fetch my post over to slash API endpoint. So the client code, remember, this is confusing, server and index.js, client and index.html. I'm going to move over here. This, what I'll do is I'll choose to send this latitude and longitude as soon as I've received it. This is what I did in the previous video. And so now, what I can do is I'll setup-- I'm just going to make up an object called Data, and what I want to send is the latitude and longitude inside of an object. So that's what I want to send. So you might think all I need to do if I were just doing a regular Fetch, right? I just wanted to fetch something, that's a Get, regular Get request like I did in previous videos, I would then just say this. Hey, fetch me the stuff from slash API, and I might actually do that a little later when I just do a Get request and get the data that's in the database. But right now, what I want to do is send a POST. In order to send a POST, I need a second argument here, which is just a JavaScript object. I'm going to call it options, and that way I can set it up separately as a variable and kind of examine it more closely. The first property that I need to put in options is the method that I'm using. And that method is a POST. Now, there's a lot of information that you can put here under Options. And if you want to look at all the possibilities, I refer you back to the MDN web docs. There's a nice page here about fetch and we can kind of see all the stuff. OK, what mode and cash and credentials, but really what I need, what I want, the key thing that I want is body. So the body of the POST request is where I'm packaging up all of my data. And you can see here, even though there are different ways to send the data, what I want to do is send it as a string text. I want to stringify, take the JavaScript object data and make it into a JSON string. So I want exactly this right here. And there's one other piece that's important. I am specifically sending data in JSON format. So it's useful to specify that in something called a header. A header is something that can be packaged along with any POST or Get request that's moving between client and server, and it's a way of adding some additional meta information. You can read more about this also on the Mozilla docs. Headers have a name, a colon, and a value. And so the one that I want to use here, I can actually just go and grab it from here, which is this content type application JSON. I'm going to grab this and I'm also going to put this here in my code. So even though there's more that I could put, I the basic pieces that I need are, hey, I want this data to get sent as JSON. I want to tell you that it's going to be JSON and I want to post it to the API. So now we're good, right? So I get the location data, I put it into a JavaScript object, I package it as a POST, and I send it to my endpoint. And in the server, I receive a console log. Let's see what happens. So I'm going to say node index.js to run the server. I'm going to go back to the browser, I'm going to refresh my page, I probably should put some console logging in the client to see-- but presumably now, it's sensing the server. I don't see an error here, I go back to the server-- whoa, so this is good news. It console-logged something. Oh, as you might have noticed, there's a ton of information as I scroll through this, crazily. While there might be points at which I need to examine certain aspects of all of the metadata that's part of the request, all I really want to look at is the body. So let me now say console log request.body. Now, one thing I should mention, by the way, is notice how I have to re-run the server every single time I change it, there is a utility that I could use called Node Mon or node monitor, and I could install it as a global node module. [MUSIC PLAYING] And if I choose to use it, I can say now, Node Mon for node monitor index.js. And anytime I change the code it's going to rewrite the-- sorry, anytime I change the code, it's going to rerun the server. So, for example, I'm going to go here and say, console.log, I got a request. And over here, you'll notice it restarted the server. Sometimes you could run into trouble with this if you're doing a lot of things at once and I often prefer to manually stop and start the server. But for right now, this might be useful. So let me leave that there for right now. Then I'm going to go over here and hit refresh. And presumably it sent the data-- oh, it must have sent the data. Presumably it sent the data. I'll go back to the server. I got a request. Undefined, undefined. Why is it undefined? I forgot one of the steps that I told you about. So I did two of them, right? I set up my route called API to receive the request. I also modified the fetch function to send data as a POST. What I did not do was add to my server the ability to parse any incoming data as JSON. The way to do that is with the express function express.json. So, similarly to how I used express.static to say, I want to host-- I want this server to host static files, I'm going to say express.json because I want this server to be able to understand incoming data as JSON. So In the code I want to do just like I did up here, app.use express.static, I'm going to say app.use express.json. And then I can actually put some options in here to control or limit what is possible in terms of receiving data. So all of that is documented here on the Express website. Let's add just as an example this limit. So Limit allows me to specify the maximum size of anybody that's coming in. So I'll say a limit. Let's just say one megabyte as a kind of starting point. So this protects against flooding my server with huge amounts of data, potentially. There's more to protecting your server than just that, but we're seeing an inkling of this here. All right. So now we can see Node Mon has restarted my server a bunch of times and I should be able to go back to the webpage and hit Refresh. And it's going to get the latitude and longitude, and now I should see the server-- ha-ha, I got a request and I got the latitude and longitude. So the server has successfully received the data. This is what I wanted to do in this video. So in a way, I'm done. Oh, that's exciting. What I've actually done here is pretty terrible in that it is required that you complete a request. So if a Get request or a POST request is coming into the server, I need to do something to complete it. The nicest thing to do if I'm trying to be polite here, which it's good for your server to be polite and send a response back. But at a minimum, I can just say response.end. So this is required to do something. What I think that I would like to do which makes more sense is say response.json, which is a function that will send data. I can also say response.send for just a short message as a string, but I want to send maybe an object back with some data in it. So I'm going to do response.json, and then I would say-- I could say like status. I'm just making this up. Success. And then maybe I'll just repeat back what was said to me. This is the therapy server, it listens and then it just repeats it back to you. So I'll say latitude, lat, longitude, lon. So this is what I want to send back now as JavaScript. OK. So then in the client I need to do something to receive this. So if I go back to index.html, what I have here calling the fetch function is where I'm sending the data, and Fetch returns a promise. So I can just say dot then, and then handle the response. Response console.log.response. All right. So let's take a look at this in the browser now. I'm going to hit refresh. It's retrieving my latitude and longitude, it's going to send this to the server, and then here we are, the response. Oh, boy. Look at this. Lat is not defined. Let's look at my code back on the server-- oh, yes. These aren't a thing. Remember, everything is in request.body. So what I could do is say data equals-- I could put this in another variable. And then I could just say data dot-- I could just say request.body.lat, data.lon. OK. There we go. Let's try this again. So the server should be restarting now any time I make changes because I'm running Node Mon, then I could just go back to the client and hit Refresh. And there is, the response. Now, this isn't what I was looking for. And if you recall from when I first looked at the Fetch function in this whole series, when Response comes back after a Fetch call, it comes in as a data stream. So it's up to you to specify how you want to read that, is it text, is it a blob, is it json, and I want to read this as JSON. So I've got a handle that in the client. And I could use another dot then, but it might be nice to make this an async function, right? This callback inside of get current position can actually be an async function with the async keyword, and then I can use-- wait, so I'm going to say const response equals await Fetch API options, then const json. I'll just maybe call it data. There's a wait response.json, and then console log that data. OK. Now I didn't change anything in the server, even if I did, Node Mon going to rerun it for me. Now I should be able to refresh here. Data has already been declared. I'm reusing-- I already use data up here, so let's just call this json. One of the nice things about using or let is it's going to enforce these kind of things to not by action use the same variable. And there it is. Status success and latitude and longitude. [BELL RINGING] We have completed this feature to review. We have now a server that hosts a static file. So when I go and load the server into my browser, I see index.html. The JavaScript HTML locates the latitude and longitude, sends that with a POST to the server, the server receives it, console logs it out, and sends it back saying, I got it. That handshake is complete, the data is exchanged. Usually when I finish these videos I like to give you a little exercise to do, so here's one. The goal, what I'm going to do with the next video is actually save the latitude and longitude along with a timestamp to a database so that I can keep this history of all of my latitude and longitudes over time. Two steps along the way to using a database is, number one, just make a variable, a variable like an array. Every time you get that latitude and longitude save that latitude and longitude into an array. That is persistence. Of course, once you quit the server and restart the server, it's lost. So another thing you could try to do, and this requires some detective work, is look up the Node file system package. Maybe you could use the node file system package to save all of the stuff in that array to a text file. And you can always load that text file, maybe it's JSON format, maybe it's plain text, maybe it's even CSV. Also, while you're doing this, whether you're saving the latitude longitude to an array or a text file, you might want to add a button to your HTML page so that every time you click that button that's when you send the latitude and longitude to the server itself. So this is something that you can really start with, and I will actually implement this and have two examples that show it just storing it an array and then saving it to a local JSON file. But what I'm going to come back to in the next video is a bit more direct. I'm going to use a database node package called NeDB to actually save to a database, and I'll talk about what a database is and what some of the advantages are in the next video. So see you there. [BELL RINGING] [MUSIC PLAYING]
A2 server json data request longitude latitude 2.3 HTTP Post Request with fetch() - Working with Data and APIs in JavaScript 1 0 林宜悉 posted on 2020/04/06 More Share Save Report Video vocabulary