Communicating data between the client and server is a two-way street, not only do we need to send data from the server to the client, but we often need to update our server-side data based on information received from the client. Therefore, we'll see how to modify data on the server based on client-side input.
Specifically, we'll use the HTTP POST
method, which is designed to send data in a request to a server.
Imagine a user who wants to add a new blog post. They'd fill in the details on our client-side app, which would then package this data and send it over to our server using Axios
. Let's see what the client-side code for this might look like:
In this code, we're sending a new post to our server using axios.post()
. The new post data is included in the request. Once the server receives the POST request, it sends back a response to the client with information such as if the POST request was successful or not. Here, we see the server’s response is response.data.user.id
.
Let's see how we can set up our server to receive this POST request and add the new post to our data:
In this code, our server is set up to receive a POST request at the /api/posts
endpoint. The req.body
contains the data our client sent - the new post. We then add this new post to our posts
array and send the newly added post back in the response.
By running the above code, you can now add new posts to your server data through your client app! This prepares you for a bit more realistic handling of server data in your future web development endeavors.