Go Full-Stack With Node.js, Express, and MongoDB
Receive Stuff From the Front-End App
Since you don’t have the database set up, you can’t store any data sent by the user for now. However, you can at least make sure that you are receiving data from the front end correctly. The front-end app has a “Sell a thing” form, which sends a POST request containing the thing for sale to the api/stuff
endpoint. Let’s see how to capture that data.
To handle the POST request coming from the front-end app, you’ll need to extract its JSON body. To do this, all you need is a simple piece of middleware provided with the Express framework. Just after you declare the app
constant, add the following:
app.use(express.json());
This tells Express to take any incoming request that has Content-Type application/json
and make its body
available on the req
object, allowing you to write the following POST middleware:
app.post('/api/stuff', (req, res, next) => {
console.log(req.body);
res.status(201).json({
message: 'Thing created successfully!'
});
});
Make sure that you either:
-
Change the method from
use
toget
for the GET request middleware. -
You could also place the POST route above the middleware for GET requests, as the GET logic will currently intercept all requests to your
/api/stuff
endpoint. Placing the POST route beforehand will intercept POST requests, preventing them from reaching the GET middleware.
Now, if you fill in the front-end app form and submit it, you should see the object you just created logged to your Node console!
Let’s Recap!
-
The middleware you set will only respond to POST requests using
app.post()
instead ofapp.use()
.
What Did You Learn in This First Part of the Course?
-
You set up your development environment, with all of the dependencies you need to get started.
-
You spun up your first Node server and used it to serve your first Express app.
-
You created two routes for your app, and implemented CORS to make sure the front end could safely make calls to your app.
In the next part of the course, you will add the essential MongoDB database layer to your app to render it fully dynamic.