• 10 heures
  • Moyenne

Ce cours est visible gratuitement en ligne.

course.header.alt.is_video

course.header.alt.is_certifying

J'ai tout compris !

Mis à jour le 21/02/2022

Create a POST Route

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!'
  });
});

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 of  app.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.

Exemple de certificat de réussite
Exemple de certificat de réussite