How it works...

Running this server is practically the same as with our very basic Node one:

> npm run build
> node out/hello_world.js
Mini server (with Express) ready at http://localhost:8080/!

We can do the same tests as earlier, and note the following:

  • Accessing the / address gets back a Server alive message 
  • Other paths produce a 404 (Not Found) error:
> curl 127.0.0.1:8080
Server alive, with Express!

Trying to access other paths (or /, but not with GET) will return a 404 error and a HTML error screen:

 The basic Express configuration shows an error screen for 404 (Not Found) errors

The key line is the app.get("/", (req, res) => ...) call. Basically, after having created the application object (app) you can specify a route (in this case, /), a HTTP method (such as .get(), .post(), .put(), and .delete()), and a whole lot more.

Go to https://expressjs.com/en/4x/api.html#app.METHOD for more on the available methods.

You can also use .all() as a catch-all for every possible method, and a function that will get called when the user hits that particular path. In our case, no matter what the request (req) is, the response (res) is constant, but obviously you'd want to do more for an actual service!

It goes without saying that you will surely have more than one route, and possibly process not only GET methods. You can certainly add many more routes and methods, and we'll get to more advanced routing in upcoming sections.

The other interesting line is app.listen(), which specifies what port to listen to, and a function that will be executed when the server starts up; in our case, it's just a log message. 

Now that we have managed to get our server running, let's implement some other usual server functionality.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.211.87