Viết API đầu tiên của bạn bằng Node.js và Express: Thiết lập Server

1

// Require packages and set the port

2

const

express

=

require

(

'

express

'

);

3

const

port

=

3002

;

4

const

bodyParser

=

require

(

'

body-parser

'

);

5

const

app

=

express

();

6

7

// Use Node.js body parsing middleware

8

app

.

use

(

bodyParser

.

json

());

9

app

.

use

(

bodyParser

.

urlencoded

({

10
    

extended

:

true

,

11

}));

12

13

app

.

get

(

'

/

'

,

(

request

,

response

)

=>

{

14
    

response

.

send

({

15
        

message

:

'

Node.js and Express REST API

'

}

16
    

);

17

});

18

19

// Start the server

20

const

server

=

app

.

listen

(

port

,

(

error

)

=>

{

21
    

if

(

error

)

return

console

.

log

(

`Error:

${

error

}

`

);

22

23
    

console

.

log

(

`Server listening on port

${

server

.

address

().

port

}

`

);

24

});