官术网_书友最值得收藏!

Setting up Express.js

As always, we need a root file loaded with all the main components that combines them to a real application.

Create an index.js file in the server folder. This file is the starting point for the back end. Here's how we go about it:

  1. First, we import express from node_modules, which we just installed. We can use import here since our back end gets transpiled by Babel. We are also going to set up webpack for the server-side code in a later in Chapter 9, Implementing Server-Side Rendering.
import express from 'express';
  1. We initialize the server with the express command. The result is stored in the app variable. Everything our back end does is executed through this object.
const app = express();
  1. Then, we specify the routes that accept requests. For this straightforward introduction, we accept all HTTP GET requests matching any path, by using the app.get method. Other HTTP Methods are catchable with app.postapp.put, and so on.
app.get('*', (req, res) => res.send('Hello World!'));
app.listen(8000, () => console.log('Listening on port 8000!'));

To match all paths, you use an asterisk, which generally stands for any in the programming environment, as we have done it in the preceding app.get line.

The first parameter for all app.METHOD functions are the path to match. From here, you can provide an unlimited list of callback functions, which are executed one by one. We are going to look at this feature later in the Routing with Express.js section.

A callback always receives the client request as the first parameter and the response as the second parameter, which the server is going to send. Our first callback is going to use the send response method.

The send function sends merely the HTTP response. It sets the HTTP body as specified. So, in our case, the body shows Hello World!, and the send function takes care of all necessary standard HTTP headers, such as Content-Length

The last step to make our server publicly available is to tell Express.js on which port it should listen for requests. In our code, we are using 8000 as the first parameter of app.listen. You can replace 8000 with any port or URL you want to listen on. The callback is executed when the HTTP server binding has finished, and requests can be accepted on this port.

This is the easiest setup we can have for Express.js.

主站蜘蛛池模板: 张家港市| 团风县| 南靖县| 阿克苏市| 永丰县| 买车| 安庆市| 芜湖县| 丹江口市| 旺苍县| 遵义县| 定结县| 马公市| 文昌市| 金华市| 漠河县| 乌拉特后旗| 临安市| 黄大仙区| 安福县| 金湖县| 宣化县| 东乌珠穆沁旗| 屯留县| 高要市| 会同县| 湖南省| 定襄县| 万载县| 高青县| 陆良县| 定西市| 枝江市| 扬州市| 兴义市| 北辰区| 筠连县| 垫江县| 龙胜| 湘潭市| 榆中县|